1

我编写了一个生成两个类的代码,我将它们写入缓冲区并使用 JavaCompiler 编译它们。我的类在 .java 文件中是这样的;

public class A{
    public A() { }
    public String toString(){ return "A";}
    }

public class B extends ArrayList<A> {
public B() {
    super();
}

public void addItem(A a) 
{
    this.add(a);
}

public void print() {
    this.print();
    }
}

像这样的东西。

但是,类的名称是随机生成的,当我创建文件时,它会出现这样的错误;

symbol:   class A
location: class B  

./src/A.java:4: error: cannot find symbol

(第 4 行是“...extends ArrayList...”,并且 A 下有一个 ^ 符号)

我的代码生成器是这样编译的;

首先,我用我的 A 类型类模板填充缓冲区,然后像这样编译:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, f.getPath());

之后,我创建另一个缓冲区并用我的 B 类型类模板填充它,然后像这样编译;

System.out.println(f.getParentFile().getPath());
compiler.run(null, null, null, f.getPath());

f 是;

f = new File(("./src/" + name + ".java"));

我怎么解决这个问题?

4

2 回答 2

1

A如评论中所述,编译器在编译类时需要了解类B。在下面的示例中,我们将已编译类的输出目录添加到/tmp/bin/编译器的类路径中optionList

如果您不需要它们,您可以阻止在文件系统上创建源文件

public class CompileDependent {

    public static void main(String[] args) {
        String sourceClassA = "public class A {"
                + "  public String toString() {"
                + "    return \"A\";"
                + "  }"
                + "}";
        String sourceClassB = "import java.util.ArrayList;"
                + "class B extends ArrayList<A> {"
                + "  public void addItem(A a) {"
                + "    this.add(a);"
                + "  }"
                + "}";

        List<JavaFileObject> compilationUnits = new ArrayList<>();
        compilationUnits.add(new StringJavaFileObject("A.java", sourceClassA));
        compilationUnits.add(new StringJavaFileObject("B.java", sourceClassB));

        List<String> optionList = new ArrayList<>();
        // classpath from current JVM + binary output directory
        optionList.add("-classpath");
        optionList.add(System.getProperty("java.class.path") + ":/tmp/bin");
        // class output directory
        optionList.add("-d");
        optionList.add("/tmp/bin");

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(
                null,
                Locale.UK,
                Charset.forName("UTF-8")
        );

        boolean compiled = compiler.getTask(
                null,
                fileManager,
                null,
                optionList,
                null,
                compilationUnits).call();
        System.out.println("compiled = " + compiled);
    }

    private static class StringJavaFileObject extends SimpleJavaFileObject {

        final String code;

        StringJavaFileObject(String name, String code) {
            super(URI.create("string:///" + name), Kind.SOURCE);
            this.code = code;
        }

        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return code;
        }
    }
}

或者您在文件系统上创建 Java 源文件。与上面类似的代码,对compilationUnits. 假定文件已存储在给定位置。

List<File> sourceFiles = new ArrayList<>();
sourceFiles.add(new File("/tmp/A.java"));
sourceFiles.add(new File("/tmp/B.java"));
于 2016-01-28T14:12:54.913 回答
0

这应该有帮助

    public void CompileClasses(ArrayList<String> classesNames){
    //File helloWorldJava = new File("classes\\"+className+".java");
    try {
        List<String> optionList = new ArrayList<String>();
        optionList.add("-classpath");
        optionList.add(System.getProperty("java.class.path") + ";dist/InlineCompiler.jar");
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
        Iterable<? extends JavaFileObject> compilationUnit=null;
        ArrayList<File> files = new ArrayList<>();
        for (String className:classesNames) {
        files.add(new File(className+".java"));
        }
        compilationUnit = fileManager.getJavaFileObjectsFromFiles(files);
        JavaCompiler.CompilationTask task = compiler.getTask(
                null,
                fileManager,
                diagnostics,
                optionList,
                null,
                compilationUnit);
        if (task.call()) {
            URLClassLoader classLoader = new URLClassLoader(new URL[]{new File("./").toURI().toURL()});
        } else {
            for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
                System.out.format("Error on line %d in %s%n %s",
                        diagnostic.getLineNumber(),
                        diagnostic.getSource().toUri(),
                        diagnostic.toString());
            }
        }
        fileManager.close();
    } catch (IOException exp) {
        exp.printStackTrace();
    }

}
于 2019-01-25T12:53:56.567 回答