【问题标题】:how to run code compiled by JavaCompiler?如何运行JavaCompiler编译的代码?
【发布时间】:2010-01-28 18:21:54
【问题描述】:

有没有办法运行JavaCompiler编译的程序? [javax.tools.JavaCompiler]

我的代码:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, prepareFile(nazwa, content));
    task.call();

    List<String> returnErrors = new ArrayList<String>();
    String tmp = new String();
    for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
        tmp = String.valueOf(diagnostic.getLineNumber());
        tmp += " msg: "+ diagnostic.getMessage(null);
        returnErrors.add(tmp.replaceAll("\n", " "));
    }

现在我想以 1 秒的生命周期运行该程序并将输出输出到字符串变量。有什么办法可以做到吗?

【问题讨论】:

    标签: java java-compiler-api jsr199


    【解决方案1】:

    你需要使用反射,类似这样:

    // Obtain a class loader for the compiled classes
    ClassLoader cl = fileManager.getClassLoader(CLASS_OUTPUT);
    // Load the compiled class
    Class compiledClass = cl.loadClass(CLASS_NAME);
    // Find the eval method
    Method myMethod = compiledClass.getMethod("myMethod");
    // Invoke it
    return myMethod.invoke(null);
    

    当然可以根据您的需要进行调整

    【讨论】:

    • 但是程序的生命周期呢?我在我的网络应用程序中使用了它。它是基于 Spring 的用于学习 Java 的 Web 应用程序。如果学生无限循环......
    • 保护这样的应用程序是一个很好的问题,但它也是一个非常不同的问题。
    • CLASS_OUTPUT 来自哪里?
    【解决方案2】:

    您必须将编译后的类添加到当前的类路径中。

    有多种方法可以做到这一点,具体取决于您的项目的设置方式。这是一个使用 java.net.URLClassLoader 的实例:

    ClassLoader cl_old = Thread.currentThread().getContextClassLoader();
    ClassLoader cl_new = new URLClassLoader(urls.toArray(new URL[0]), cl_old);
    

    其中“urls”是指向文件系统的 url 列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-31
      • 2013-10-10
      相关资源
      最近更新 更多