cacert
cacert

Reputation: 2797

Listing and loading class within jar

In a project i need to load different jar files under a specific directory. Then i will search .class files which implements a specific interface. and when i found searched one, i need to load it with Class.forName(). Is there an easy way to do all this? Can you propose some sample code ?

Upvotes: 0

Views: 146

Answers (3)

Johannes Wachter
Johannes Wachter

Reputation: 2735

I also like the approach of Mark if your in a plain Java Application and want to define the Interface <-> Implementation(s) mapping upfront.

Another way of doing what you want I think is tinker with classpath scanning where you consider the currently running classpath and use it to find components by Annotation or Interface.

Popular example for this is for example Spring.

To use that outside of Spring you could try using some library like Reflections or Class-Search which offer an API to search inside the classpath.

Since I recently tinkered with Vaadin/GWT and their approach to find something inside the current classpath, this class from their tools could be interesting for you as well if you want to implement something like that manually.

But like Martijn already mentioned these solutions would need to add the JAR to your classpath so the class gets loaded and then interpret the found components.

If that's critical and you can't load the class upfront and interpret it later, you could try to build something above a library like ASM which can perhaps offer interpretation of a .class-file without loading the class.

Upvotes: 1

Mark Rotteveel
Mark Rotteveel

Reputation: 109253

Take a look at ServiceLoader. This does require the implementer of these classes to supply a descriptive file in /META-INF/services/<fqn-of-interface> listing all implementation classes provided by the jar for that interface.

Upvotes: 3

Martijn Courteaux
Martijn Courteaux

Reputation: 68907

I'm pretty sure you can't check if the class implements a specific interface without loading it first. So, I think you have to load every class file or try to solve your problem/achieve your target a different way.

You could try to read the .class file binary and find out in the byte code which interface it implements, but don't ask me how to do this. :)

Upvotes: 1

Related Questions