Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

java - How to provide an interface to JavaCompiler when compiling a source file dynamically?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...