How to set classpath for com.sun.tools.javac.Main.compile () function?

I am using the com.sun.tools.javac.Main.compile() function to compile a java file at runtime from my struts projects. But for some files, they need some specific banks, such as axis2. I have banks, but how can I set them in the classpath to compile the java file at runtime? I tried with System.setProperty("java.class.path","jar dir"); but could not compile.

+6
source share
1 answer

The following code that uses com.sun.tools.javac.Main worked for me:

Apple.java

 //This class is packaged in a jar named MyJavaCode.jar import com.xyz.pqr.SomeJavaExamples; public class Apple { public static void main(String[] args) { System.out.println("hello from Apple.main()"); } } 

AClass.java

 import com.sun.tools.javac.Main; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class AClass { public static void main(String[] args) { try { //Specify classpath using next to -cp //This looks just like how we specify parameters for javac String[] optionsAndSources = { "-g", "-source", "1.5", "-target", "1.5", "-cp", ".:/home/JavaCode/MyJavaCode.jar", "Apple.java" }; PrintWriter out = new PrintWriter(new FileWriter("./out.txt")); int status = Main.compile(optionsAndSources, out); System.out.println("status: " + status); System.out.println("complete: "); }catch (Exception e) {} } } 

Note. To compile this AClass.java , tools.jar must be in the classpath , which is missing by default, so you will need to specify it.

If you are using Java 1.6 , you should use javax.tools.JavaCompiler instead, its getTask ( ) methods accept an options argument that may have a classpath .

For instance:

 import javax.tools.JavaCompiler; import javax.tools.ToolProvider; import javax.tools.JavaFileObject; public final class AClass { private static boolean compile(JavaFileObject... source ){ List<String> options = new ArrayList<String>(); // set compiler classpath to be same as the runtime's options.addAll(Arrays.asList("-classpath", System.getProperty("java.class.path"))); //Add more options including classpath final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); final JavaCompiler.CompilationTask task = compiler.getTask(/*default System.err*/ null, /*std file manager*/ null, /*std DiagnosticListener */ null, /*compiler options*/ options, /*no annotation*/ null, Arrays.asList(source)); return task.call(); } 

com.sun.tools.javac.Main deprecated and not documented.

+2
source

Source: https://habr.com/ru/post/924433/


All Articles