javacompiler并没有真正编译这个类

mbzjlibv  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(324)

我想使用反射来获取新创建的java类的所有方法。像bellow一样,我通过从另一个文件复制创建了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);
4smxwvx5

4smxwvx51#

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();
}

最后用上述方法成功地编译了target service.java。谢谢大家。

yebdmbv4

yebdmbv42#

Method[] declaredMethods = Service.class.getDeclaredMethods();

不能编写直接依赖于 Service.class 除非 Service 已编译。您必须动态加载类并从中获取方法。目前很难看到包含此代码的类是如何加载的,而且它肯定不会给出正确的答案,除非 Service.class 在加载类时存在,在这种情况下,代码将给出该版本的方法,而不是新编译的版本。
你需要去掉所有提到 Service.class 或者确实如此 Service 从整个源代码中 ServiceClass.forName() 编译后。做一个干净的建设,以确保没有 Service.class 文件存在于部署中。

相关问题