代码之家  ›  专栏  ›  技术社区  ›  brice

如何在动态编译源文件时为JavaCompiler提供接口?

  •  7
  • brice  · 技术社区  · 14 年前

    我试图在运行时编译并加载一个类,而不知道该类的包。我知道类应该符合接口和源的位置(以及类名)。我正在尝试以下操作:

    /* Compiling source */
    File root = new File("scripts");
    File sourceFile = new File(root, "Test.java");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    compiler.run(null, null, null, sourceFile.getPath());
    

    test.java文件看起来像

    import foo.Itest;
    public class Test implements Itest{
    ...
    }
    

    我得到一个 cannot find symbol symbol : class Itest 编译器出错我该怎么办 为编译器提供接口 (已加载)以避免此错误?

    [编辑-已解决]: 错误源于接口是 ITest 消息来源提到 Itest 接口。

    4 回复  |  直到 7 年前
        1
  •  2
  •   Community CDub    8 年前

    似乎 compiler.run() 正在外部运行,需要设置类路径。是否尝试使用最后一个参数向它传递合适的类路径设置 args run() 打电话?也许这就是为什么 ToolProvider.getSystemToolClassLoader() .

    这个 stackoverflow post 或许也能帮到你。

        2
  •  1
  •   Community CDub    8 年前

    不确定这是不是你要找的,但是,正如@phil提到的 here ,您可以尝试在 compiler.run 方法

        3
  •  -1
  •   Maurice Perry    14 年前

    你考虑过用 javassist 或者类似的?