6

我正在使用com.sun.tools.javac.Main.compile()函数在运行时从我的 struts 项目编译 java 文件。但是对于某些文件,他们需要一些特定的 jar,例如axis2。我有罐子,但如何将它们设置为类路径以在运行时编译 java 文件?我尝试过System.setProperty("java.class.path","jar dir");但无法编译。

4

1 回答 1

2

以下代码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()");
    }
}

类.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.javatools.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也已弃用且未记录。

于 2012-09-03T10:48:37.893 回答