如何为com.sun.tools.javac.Main.compile()函数设置类路径?
我正在使用com.sun.tools.javac.Main.compile()
函数从我的struts项目中运行时编译java文件。 但对于某些文件,他们需要一些像axis2这样的特定jar子。 我有jar子但是如何将它们设置为classpath以在运行时编译java文件? 我尝试过System.setProperty("java.class.path","jar dir");
但未能编译。
以下使用com.sun.tools.javac.Main
代码为我工作:
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) {} } }
注意:要编译此AClass.java
, tools.jar
需要位于classpath
,默认情况下不存在,因此您必须指定它。
如果您使用的是Java 1.6
那么您应该考虑使用javax.tools.JavaCompiler
,它的getTask( )方法接受一个可以具有classpath
的参数options
。
例如:
import javax.tools.JavaCompiler; import javax.tools.ToolProvider; import javax.tools.JavaFileObject; public final class AClass { private static boolean compile(JavaFileObject... source ){ List options = new ArrayList (); // set compiler's 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
也已弃用且未记录。