[英]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.