関数を使用com.sun.tools.javac.Main.compile()
して、struts プロジェクトから実行時に Java ファイルをコンパイルしています。ただし、一部のファイルでは、axis2 などの特定の jar が必要です。私はjarを持っていますが、実行時にjavaファイルをコンパイルするためにそれらをクラスパスに設定するにはどうすればよいですか? で試しましSystem.setProperty("java.class.path","jar dir");
たが、コンパイルに失敗しました。
5210 次
1 に答える
2
使用する次のコード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
使用を検討する必要があります。そのgetTask( ) メソッドは、.javax.tools.JavaCompiler
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
非推奨であり、文書化もされていません。
于 2012-09-03T10:48:37.893 に答える