如何加载未编译的 Java 类?
你需要先编译它。这可以通过编程来完成javax.tools API。这仅需要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 = Files.createTempDirectory("java").toFile();
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.getDeclaredConstructor().newInstance(); // Should print "world".
System.out.println(instance); // Should print "test.Test@hashcode".
其产量如下
hello
world
test.Test@cafebabe
如果这些类进一步使用会更容易implements
已经在类路径中的某个接口。
SomeInterface instance = (SomeInterface) cls.getDeclaredConstructor().newInstance();
否则你需要让反射API访问和调用(未知)方法/字段。
这就是说,与实际问题无关:
properties.load(new FileInputStream(new File("ClassName.properties")));
Letting java.io.File
依赖当前工作目录会带来可移植性问题。不要那样做。将该文件放入类路径并使用ClassLoader#getResourceAsStream()具有类路径相对路径。
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("ClassName.properties"));