I have been trying to compile some Java Classes in a String using java. I have used javax.tools.JavaCompiler to compile the Classes in the Strings.
I have made instances of SimpleJavaFileObject by a Subclass that I have made of SimpleJavaFileObject.
import javax.tools.SimpleJavaFileObject;
import java.net.URI;
public class JavaSourceFromString extends SimpleJavaFileObject {
final String code;
public JavaSourceFromString(String name, String code) {
super( URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension),Kind.SOURCE);
this.code = code;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return code;
}
}
and I have made Instances of this class, added it to an ArrayList, then Got the
ToolProvider.SystemJavaCompiler();
and added compilation options. and then Compiled
Iterable<? extends JavaFileObject> fileObjects = jsfsList;
JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
if (jc == null) throw new Exception("Compiler unavailable");
List<String> options = new ArrayList<>();
options.add("-d");
options.add(Config.getProperty("DESTINATION_PATH"));
options.add("-classpath");
URLClassLoader urlClassLoader = (URLClassLoader)Thread.currentThread().getContextClassLoader();
StringBuilder sb = new StringBuilder();
for (URL url : urlClassLoader.getURLs()) {
sb.append(url.getFile()).append(File.pathSeparator);
}
sb.append(PiranhaConfig.getProperty("DESTINATION_PATH"));
options.add(sb.toString());
StringWriter output = new StringWriter();
boolean success = jc.getTask(output, null, null, options, null, fileObjects).call();
if (success) {
LOG.info("Class [" + compiledClasses + "] has been successfully compiled");
} else {
throw new Exception("Compilation failed :" + output);
}
I have tested this with 3 classes that have circular dependency. it gives the error that it cannot find the symbol of a reference. it seems that unlike javac, this Compiler looks at each item in the list individually and tries to compile each alone.
how to achieve the same result as Javac using this compiler?? Someone please point me in the right direction :) Thanks.