Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access java classes in a subfolder

I'm trying to make a program that can load an unknown set of plugins from a sub-folder, "Plugins". All of these plugins implement the same interface. What I need to know is how do I find all of the classes in this folder so that I can instantiate and use them?

like image 982
Lord Jragon Avatar asked Mar 04 '26 01:03

Lord Jragon


1 Answers

MyInterface.java

A stub interface.

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

TestClass.java

A test class to be loaded, implementing your interface.

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

(Compiled class file placed in "subfolder/".)


Test.java

A complete test program that loads all class files from "subfolder/" and instantiates 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) {
        }
    }
}

Output from Test program above:

Loading TestClass.class
Hello World, from TestClass

like image 144
aioobe Avatar answered Mar 05 '26 16:03

aioobe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!