testing for a class having been loaded

Alan Snyder javalists at cbfiddle.com
Wed Nov 30 15:51:58 UTC 2016


> On Nov 30, 2016, at 1:46 AM, Alan Bateman <Alan.Bateman at oracle.com> wrote:
> 
> On 29/11/2016 21:14, Alan Snyder wrote:
> 
>> Prior to JDK 9, it was possible (using setAccessible) to ask a ClassLoader whether a class with a given name had been loaded without actually forcing it to be loaded.
>> 
>> This hack will not work in JDK9, so I am wondering if there is a way to do this?
>> 
>> If not, can someone explain why it would be a bad thing to be able to do this?
> I can't quite tell what the hack is, is it reading the private `classes` field?
> 


As Michael said, the hack is using reflection with setAccessible() to call the protected method ClassLoader::findLoadedClass().

Is there some conceptual or security reason to not provide this functionality in a public API?


>> 
>> Here is my use case:
>> 
>> I have two classes, A and B, that have been designed to be aware of each other, but are packaged in separate JAR files or modules that can be loaded independently. My goal is for these classes to make a runtime connection with each other, but only if both have been loaded by the application.
>> 
>> If each class can at load (initialization) time test whether the other has been loaded, then they can use reflection to make that connection.
>> 
>> All of the other solutions I have thought of require yet a third class/interface C that is separately packaged and loaded by both A and B. This is feasible, but seems unnecessary.
>> 
> The scenario sounds like it needs a broker but without specifics then it's hard to make suggestions.
> 
> One question: Are A and B in different packages? If A is p.A and B is q.B when would it be enough to know if any p.* or q.* types have been loaded? If so then ClassLoader::getDefinedPackage might be useful.

ClassLoader::getDefinedPackage might be useful in a new design, especially one using modules, as split packages are not allowed.

However, I’m not sure of the implications of this method not searching ancestor class loaders. Might there be circumstances where the result is not consistent with findLoadedClass()?

  Alan



More information about the jigsaw-dev mailing list