How to provide an interface to JavaCompiler when c

2019-02-09 14:31发布

I'm trying to compile and load a class at runtime, without knowing the package of the class. I do know that the class should comply with an interface, and the location of the source, (and hence the class name). I'm trying the following:

/* 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());

where the Test.java file looks something like

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

And I get a cannot find symbol symbol : class Itest error from the compiler. How do I provide the compiler with the interface (which has already been loaded) to avoid this error?

[EDIT - RESOLVED]: The error came from the fact the the interface was ITest and the source referred to an Itest interface.

4条回答
祖国的老花朵
2楼-- · 2019-02-09 15:09

It seems likely that the compiler.run() is running externally and needs the class path to be set. Have you tried to pass it a suitable class path setting using the last parameter args to the run() call? Perhaps that's why ToolProvider.getSystemToolClassLoader().

This stackoverflow post might also help you.

查看更多
倾城 Initia
3楼-- · 2019-02-09 15:22

Not sure if this is what you're looking for but, as mentioned by @Phil here, you could try to pass a classpath argument in your compiler.run method.

查看更多
来,给爷笑一个
4楼-- · 2019-02-09 15:26

jOOR supports compiling classes in memory. Your code could look like this:

Class<?> klass = Reflect.compile("foo.Test", `
    import foo.Itest;
    public class Test implements Itest {
    }
`);

Behind the scenes, javax.tools.JavaCompiler is used, but the API is simpler for every day use cases.

(Disclaimer: I work for the company behind jOOR)

查看更多
Rolldiameter
5楼-- · 2019-02-09 15:31

Have you considered generating your class with javassist or something like that?

查看更多
登录 后发表回答