Reputation: 59
I am looking for a way to find all instances currently running in the JVM that inherit a given interface, say interfaceA. The suggestion that I initially received was to use
Lookup.getDefault().lookupAll(interfaceA.class);
with
@ServiceProvider(service=interfaceA.class)
before the definition of a class implementing interfaceA. I have found that this does indeed find the classes that implement interfaceA. However, I am pretty sure that Lookup gives me a new instance of that class using java reflection. My biggest problem is that I am limited as to which libraries I can introduce into my Netbeans project, otherwise a previous question would have answered this.
Does such an animal exist in pure Java or a very well known library?
Thanks
Upvotes: 2
Views: 159
Reputation: 24192
no. since java loads classes dynamically when needed you cant really "enumerate" all of the classes available to the JVM. most of the mechanisms used to do this involve listing all the subclasses in advance somewhere (an xml file, a properties file) on the path and using that, or marking them for some sort of runtime processing (your @ServiceProvider annotation) by some container. Java EE, Spring and guice are some well known containers - but such code will not work outside such a container.
I've also seen code that attempts to iterate over all jars on the classpath but such code is very fragile and usually tied to a specific environment its running on.
Upvotes: 1