我正在动态生成一个 java 类并尝试调用它的方法。为此,似乎我必须执行以下操作
- 编译类(javac 文件名将不起作用,因为它依赖于可能的其他依赖项)
- 在运行时将类添加到类路径
我怎样才能实现这个目标?
最佳答案
我让它与 JavaCompiler 和自定义类加载器一起工作,如下所示。
private Path compileSource(Path javaFile, String contractFileNameWithoutExtension) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, javaFile.toFile().getAbsolutePath());
return javaFile.getParent().resolve(contractFileNameWithoutExtension+".class");
}
public Class findClass(String name) {
String filePath = sourceCodeLocation +"/"+ name.replace(".", "/")+".class";
byte[] b = loadClassFromFile(filePath);
return defineClass(name, b, 0, b.length);
}
private byte[] loadClassFromFile(String fileName) {
try {
InputStream inputStream = FileUtils.getFileInputStream.apply(fileName);
byte[] buffer;
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
int nextValue = 0;
try {
while ((nextValue = inputStream.read()) != -1) {
byteStream.write(nextValue);
}
} catch (IOException e) {
e.printStackTrace();
}
buffer = byteStream.toByteArray();
return buffer;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
关于java - 动态生成 Java 类并添加到类路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56285487/