我想用反射获取一个新创建的java类的所有方法。就像下面一样,我通过从另一个文件复制来创建 java 类,然后我使用 JavaCompiler 来编译新创建的 Java。但是不知道为什么没有创建目标类文件。 PS:如果我给了错误的源目标java文件路径,将会有类似“javac: cannot find file: codeGenerator/Service.java”
这样的编译信息。谢谢大家。
private static Method[] createClassAndGetMethods(String sourceFilePath) throws IOException {
File targetFile = new File("Service.java");
File sourceFile = new File(sourceFilePath);
Files.copy(sourceFile, targetFile);
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, targetFile);
Thread.sleep(5000);
//After the Service.java compiled, use the class getDeclaredMethods() method.
Method[] declaredMethods = Service.class.getDeclaredMethods();
return declaredMethods;
}
编译方法:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, targetFile);
最佳答案
Method[] declaredMethods = Service.class.getDeclaredMethods();
您不能编写直接依赖于 Service.class
的代码,除非 Service
已经编译。您将不得不动态加载该类并从那里获取方法。目前很难看出包含这段代码的类是如何加载的,它肯定不会给出正确的答案,除非 Service.class
的一个版本是在加载类时出现,在这种情况下,您的代码将提供那个版本的方法,而不是新编译的版本。
您需要从整个源代码中删除对 Service.class
或 Service
的所有引用,并使用 Service
加载 Class.forName()
编译后。执行干净的构建以确保部署中不存在 Service.class
文件。
关于JavaCompiler 并没有真正编译这个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37132574/