如何在子文件夹中访问java类 [英] How to access java classes in a subfolder
问题描述
我试图创建一个程序,可以从子文件夹插件加载未知的插件集。所有这些插件都实现相同的接口。我需要知道的是如何找到这个文件夹中的所有类,以便我可以实例化和使用它们?
MyInterface.java
存根接口。
包测试;
public interface MyInterface {
public void printSomething();
}
TestClass。 java
要加载的测试类,实现您的界面。
code> import test.MyInterface;
public class TestClass implements MyInterface {
public void printSomething(){
System.out.println(Hello World,from TestClass);
}
}
(编译类文件放在子文件夹 )
Test.java
一个完整的测试程序,从子文件夹/加载所有类文件,并实例化并运行接口方法。
包装测试;
import java.io.File;
public class Test {
public static void main(String [] args){
try {
ClassLoader cl = ClassLoader.getSystemClassLoader
文件子文件夹=新文件(子文件夹);
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){
}
}
}
$ $ $ b $ b
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?
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
这篇关于如何在子文件夹中访问java类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!