[英]how to set classpath for com.sun.tools.javac.Main.compile() function?
我正在使用com.sun.tools.javac.Main.compile()
函數在運行時從我的struts項目中編譯Java文件。 但是對於某些文件,它們需要一些特定的jar文件,例如axis2。 我有jar,但是如何將它們設置為classpath以便在運行時編譯Java文件? 我已經嘗試使用System.setProperty("java.class.path","jar dir");
但未能編譯。
以下使用com.sun.tools.javac.Main
代碼為我工作:
蘋果.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( )方法采用的參數options
可以具有classpath
。
例如:
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'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
也已棄用,也未記錄在案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.