如何加载未编译的Java类?
您需要先编译它。可以编程方式使用javax.toolsAPI..这只需要JDK安装在JRE之上的本地机器上。
下面是一个基本的启动示例(将明显的异常处理放在一边):// Prepare source somehow.String source = "package test; public class Test { static { System.out.println(\"hello\");
} public Test() { System.out.println(\"world\"); } }";// Save source in .java file.File root = new File("/java");
// On Windows running on C:\, this is C:\java.File sourceFile = new File(root, "test/Test.java");
sourceFile.getParentFile().mkdirs();Files.write(sourceFile.toPath(), source.getBytes(StandardCharsets.UTF_8));
// Compile source file.JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();compiler.run(null, null, null, sourceFile.getPath());
// Load and instantiate compiled class.URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() });
Class> cls = Class.forName("test.Test", true, classLoader); // Should print "hello".Object instance = cls.newInstance();
// Should print "world".System.out.println(instance); // Should print "test.Test@hashcode".
会产生这样的结果hello
world
test.Test@ab853b
如果这些类更容易使用,则更容易使用。implements已经在类路径中的某个接口。SomeInterface instance = (SomeInterface) cls.newInstance();
否则,您需要让反射API访问和调用(未知)方法/字段。
这与实际问题无关:properties.load(new FileInputStream(new File("ClassName.properties")));
放任java.io.File依赖当前的工作目录是解决可移植性问题的良方。别干那事。将该文件放入类路径并使用ClassLoader#getResourceAsStream()有一条类路径-相对路径。properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("ClassName.properties"));