我正在使用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
的代码为我工作:
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()方法采用参数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
也已被弃用,也未记录在案。关于java - 如何设置com.sun.tools.javac.Main.compile()函数的类路径?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12246175/