JavaCompiler';我没有真正编译这个类
我想使用反射来获取新创建的java类的所有方法。像bellow一样,我通过复制另一个文件创建了java类,然后使用JavaCompiler编译新创建的java。但是我不知道为什么没有创建目标类文件。PS:如果我给出了错误的源-目标java文件路径,那么会出现编译信息,如JavaCompiler';我没有真正编译这个类,java,java-compiler-api,javacompiler,Java,Java Compiler Api,Javacompiler,我想使用反射来获取新创建的java类的所有方法。像bellow一样,我通过复制另一个文件创建了java类,然后使用JavaCompiler编译新创建的java。但是我不知道为什么没有创建目标类文件。PS:如果我给出了错误的源-目标java文件路径,那么会出现编译信息,如“javac:not-find file:codeGenerator/Service.java”。谢谢大家 private static Method[] createClassAndGetMethods(String sourc
“javac:not-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);
除非已经编译了Service
,否则不能编写直接依赖于Service.class
的代码。您必须动态加载该类并从中获取方法。目前,很难看到包含此代码的类将如何加载,而且它肯定不会给出正确的答案,除非加载类时存在Service.class
版本,在这种情况下,您的代码将给出该版本的方法,而不是新编译的版本
您需要从整个源代码中删除对Service.class
或实际上是Service
的所有引用,并在编译后使用class.forName()
加载Service
。执行干净的生成以确保部署中不存在服务.class
文件。公共静态void编译(String sourceFilePath,String classPath)引发IOException{
public static void compile(String sourceFilePath, String classPath) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Iterable sourcefiles = fileManager.getJavaFileObjects(sourceFilePath);
Iterable<String> options = Arrays.asList("-d", classPath);
compiler.getTask(null, fileManager, null, options, null, sourcefiles).call();
fileManager.close();
}
JavaCompiler=ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager=compiler.getStandardFileManager(null,null,null);
Iterable sourcefiles=fileManager.getJavaFileObjects(sourceFilePath);
Iterable options=Arrays.asList(“-d”,类路径);
getTask(null,fileManager,null,options,null,sourcefiles).call();
fileManager.close();
}
最后,我用上述方法成功地编译了target Service.java。谢谢大家。
方法[]declaredMethods=Class.forName(“codeGenerator.Service”).getDeclaredMethods()代码>如果我这样使用它,我仍然无法获得正确的输出。事实上,这个类没有被编译。@leo,所以请看。
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;
}