Search code examples
javajarclassloader

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 ?


Solution

  • 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.