简体   繁体   中英

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 ?

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.

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. :)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM