LapisSea™
LapisSea™
JCHJava Community | Help. Code. Learn.
Created by LapisSea™ on 11/12/2024 in #java-help
How do I keep a class available to unload while keeping a MethodHandles.Lookup of it?
I have a library where a class can consent to full access of private members by registering its MethodHandles.lookup() in its static initializer. Something like this:
class Foo extends Thing{
static{ accessConsent(MethodHandles.lookup()); }

private int thingOnlyField; // Thing can now access this

...
}

class Thing{
private static final Map<Class, MethodHandles.Lookup> PRIVATE_LOOKUPS = ...
protected static void accessConsent(MethodHandles.Lookup lookup){
PRIVATE_LOOKUPS.put(lookup.lookupClass, lookup);
}
}
class Foo extends Thing{
static{ accessConsent(MethodHandles.lookup()); }

private int thingOnlyField; // Thing can now access this

...
}

class Thing{
private static final Map<Class, MethodHandles.Lookup> PRIVATE_LOOKUPS = ...
protected static void accessConsent(MethodHandles.Lookup lookup){
PRIVATE_LOOKUPS.put(lookup.lookupClass, lookup);
}
}
The private lookup gets stored inside a Map<Class, MethodHandles.Lookup>. I want to be able to give the class the freedom to unload. So when all references to the class loader and the class itself is gone. Issue is that Lookup contains a reference to the class so I would need a weakly referenced key and value map. (that is not the issue, already have that) If I do that though, the lookup itself will be randomly forgotten so that kind of defeats the whole purpose of providing it on load. Any ideas on how to best handle this?
4 replies