java - 以编程方式编译 Java 类?

标签 java compilation

我找到并修改了下面的代码以编程方式编译一个 Java 类:

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class CompileHello {

public static void main(String[] args)  {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    int result = compiler.run(null, null , null , "C:\\Users\\quickCoder\\Desktop\\Hello.java");

    System.out.println("Compile result code = " + result);
    }
}

但是,我不断收到以下错误:

Exception in thread "main" java.lang.NullPointerException
at CompileHello.main(CompileHello.java:8)

第 8 行是下面一行:

  int result = compiler.run(null, null , null , "C:\\Users\\quickCoder\\Desktop\\Hello.java");

我确保输入的文件路径是我编写的 Java 类的实际路径。

最佳答案

  1. 我怀疑问题是“编译器”在您的 Eclipse 环境中返回为“空”,但在您的 NetBeans 环境中返回非空。

  2. 注意:

http://blog.nobel-joergensen.com/2008/07/16/using-eclipse-compiler-to-create-dynamic-java-objects-2/

However to gain access to the JDK compiler you need to run your application from the JDK, and since this is not default behaviour, I choose to use the Eclipse compiler instaid. (Besides the Eclipse compiler share the same interface, so the two compilers should behave similar).

  1. 同一链接讨论了如果要在 Eclipse 环境中运行,如何指定使用 Eclipse 编译器。

  2. 但是,您可以指向任何 JDK:

How to set classpath when I use javax.tools.JavaCompiler compile the source?

关于java - 以编程方式编译 Java 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31977879/

相关文章:

java - 使用 Windows Azure 在云中安装 Red5 服务器?

java - Woodstox stax 和 java stax 冲突

java - Haskell 的类型系统是否遵循 Liskov 替换原则?

计算已编译 C 程序的代码指标

qt - 在 Ubuntu 13.04 和 QT-Creator 上设置 SFML

java - 我应该使用 Java 8 默认方法来手动实现 Spring Data 存储库方法吗?

java - 从子类到父类(super class)获取字段

compilation - 为移动设备编译 Haiku OS

javascript - typescript 生成冗余变量

c++ - 编译错误 : `Class' does not name a type