I want to use reflection to get all the methods of a newly created java class. Like bellow I created the java Class by copying from another file, then I use JavaCompiler to compile the newly created Java. But I don't know why the target class file was not created. PS: If I give the wrong source target java file path, there will be compile info like "javac: cannot find file: codeGenerator/Service.java"
. Thank you all.
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;
}
compile method:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, targetFile);