Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 905
brice Avatar asked Aug 10 '10 08:08

brice


People also ask

What is dynamic compilation in Java?

Dynamic compilation is a process used by some programming language implementations to gain performance during program execution. Although the technique originated in Smalltalk, the best-known language that uses this technique is Java.

What is dynamic code Java?

The Dynamic Code Evolution Virtual Machine (DCE VM) is a modification of the Java HotSpot™ VM that allows unlimited redefinition of loaded classes at runtime. The current hotswapping mechanism of the HotSpot™ VM allows only changing method bodies.


2 Answers

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.

like image 188
Paul Jowett Avatar answered Oct 06 '22 12:10

Paul Jowett


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.

like image 34
aioobe Avatar answered Oct 06 '22 11:10

aioobe