使用JavaCompiler以编程方式编译Java? [英] Programmatically compile java with JavaCompiler?

查看:490
本文介绍了使用JavaCompiler以编程方式编译Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从另一个Stack Overflow线程获得了Java代码

I got this Java code from another Stack Overflow thread

import java.io.*;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class Main {
  public static void main(String[] args) throws IOException{
    String source = " public class Test { public static void main(String args[]) {     System.out.println(\"hello\"); } }";

    // Save source in .java file.
    File root = new File("C:\\java\\");
    root.mkdir();
    File sourceFile = new File(root, "\\Test.java");
    Writer writer = new FileWriter(sourceFile);
    writer.write(source);
    writer.close();

    // Compile source file.
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    compiler.run(null, null, null, sourceFile.getPath());
  }
}

但是我不断收到这样的NullPointerException

But I keep getting a NullPointerException like this

Exception in thread "main" java.lang.NullPointerException
    at com.zove.compiler.Main.main(Main.java:24)

它可以执行编译,但是会在运行时引发异常. 我在做什么错了?

It does compile but it throws the exception at runtime. What am I doing wrong?

推荐答案

当我使用JDK执行代码时,您的代码对我来说很好用.如果我使用JRE执行它,则会像您一样在compiler.run(...)上收到NullPointerException.

Your code works fine for me when I execute it using the JDK. If I execute it using the JRE I get a NullPointerException on compiler.run(...) like you.

因此,我假设您只需切换Java运行时即可执行代码.

Therefore I assume that you only have to switch the Java runtime for executing your code.

这篇关于使用JavaCompiler以编程方式编译Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆