How to access Java classes in a subfolder

I am trying to create a program that can load an unknown set of plugins from the Plugins subfolder. All of these plugins implement the same interface. I need to know how can I find all the classes in this folder so that I can create and use them?

+2
source share
4 answers

MyInterface.java

The interface is a stub.

package test; public interface MyInterface { public void printSomething(); } 

TestClass.java

A loadable test class that implements your interface.

 import test.MyInterface; public class TestClass implements MyInterface { public void printSomething() { System.out.println("Hello World, from TestClass"); } } 

(A compiled class file placed in "subfolder /".)


Test.java

A complete test program that downloads all class files from the "subfolder /" and creates instances and runs the interface method on it.

 package test; import java.io.File; public class Test { public static void main(String[] args) { try { ClassLoader cl = ClassLoader.getSystemClassLoader(); File subfolder = new File("subfolder"); for (File f : subfolder.listFiles()) { String s = f.getName(); System.out.println("Loading " + s); Class cls = cl.loadClass(s.substring(0, s.lastIndexOf('.'))); MyInterface o = (MyInterface) cls.newInstance(); o.printSomething(); } } catch (ClassNotFoundException e) { } catch (InstantiationException e) { } catch (IllegalAccessException e) { } } } 

Conclusion from the test program above:

Download TestClass.class
Hello World, from TestClass

+2
source

Check java.util.ServiceLoader

A service is a well-known collection of interfaces and (usually abstract) classes. A service provider is a specific service implementation. Classes in a provider typically implement the interfaces and subclasses of classes defined in the service itself. Service providers can be installed in an implementation of the Java platform in the form of extensions, that is, jar files placed in any of the usual extension directories. Providers may also be available by adding them to the application class path or to some other platform features.

This article explains the details.

+1
source

Browse through the folder with File.listFiles () and use an instance of JarClassLoader to load the classes there.

Or add description.xml to each of these jars if they are in the classpath and use getClass (). getClassLoader (). findResources ("description.xml") to download all the descriptions, and then you have all the plugin classes to load.

0
source

To annotate your implementation classes with a special annotation and use scannotation , it performs a byte scan of class files and is order faster than anything else, you can use it to instantly search for an entire very large class.

0
source

All Articles