【问题标题】:How to compile and run inside the java program如何在java程序内部编译运行
【发布时间】:2014-09-25 06:13:41
【问题描述】:

我想使用另一个 Java 程序打开 Java GUI。
它成功编译,但无法运行。它说“无法加载主类”。这是我的代码:

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


public class Test {

  public static void main(String[] args) {
    try {
        JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
        jc.run(System.in, System.out, System.err, "src/HelloWorld.java");

        // I think this line has the error
        Runtime.getRuntime().exec("cmd.exe /c start java src/HelloWorld");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

HelloWorld 类:

import javax.swing.JFrame;
public class HelloWorld {
public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setSize(100, 500);
    frame.setVisible(true);
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

【问题讨论】:

  • 您可能希望正确格式化代码块。这将有助于问题的可读性。然后,您还可以尝试解释错误的确切位置/位置,并在适用的情况下提供某种形式的调试输出。
  • 这通常会给你一个 NullPointerException 因为 ToolProvider.getSystemJavaCompiler() 通常返回 null。你是怎么解决这个问题的?
  • 你想运行两个 main() 方法中的哪一个?您使用的是哪个 IDE?
  • @Dawnkeeper 我通过在安装的 jre 中添加 tool.jar 来解决这个问题
  • @m0skit0 我想从 Test 类运行 HelloWorld 类。我用过eclipse。

标签: java


【解决方案1】:

您的代码可能会在许多地方失败,例如,它可能由于某种原因无法编译; java 可能不在操作系统的搜索路径中; java 命令可能会失败,因为 src/HelloWorld 参数看起来错误。

我相信你的命令应该更像java -cp ./src HelloWorld 或者它应该在src 目录的上下文中执行...

您确实需要尽一切努力诊断潜在问题,例如JavaCompilerDiagnosticCollector 和阅读InputStreamErrorStream 的进程

根据您的HelloWorld.javathis previous answer,我能够生成这个示例,它可以成功编译并运行您的类...

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class TestCompile {

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder(64);

        try {
            DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null)) {
                // >>>> Compiler Stage
                // This sets up the class path that the compiler will use.
                // I've added the .jar file that contains the DoStuff interface within in it...
                List<String> optionList = new ArrayList<>();
                optionList.add("-classpath");
                optionList.add(System.getProperty("java.class.path"));

                Iterable<? extends JavaFileObject> compilationUnit
                                = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(new File("src/HelloWorld.java")));
                JavaCompiler.CompilationTask task = compiler.getTask(
                                null,
                                fileManager,
                                diagnostics,
                                optionList,
                                null,
                                compilationUnit);
                if (task.call()) {
                    // <<<< Compiler Stage
                    // >>>> Run stage...
                    ProcessBuilder pb = new ProcessBuilder("java", "-cp", "./src", "HelloWorld");
                    pb.redirectError();
                    Process p = pb.start();

                    InputStreamConsumer.consume(p.getInputStream());

                    p.waitFor();
                    // <<<< Run Stage
                } else {
                    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
                        System.out.format("Error on line %d in %s%n",
                                        diagnostic.getLineNumber(),
                                        diagnostic.getSource().toUri());
                    }
                }
            } catch (InterruptedException ex) {
                Logger.getLogger(TestCompile.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (IOException exp) {
            exp.printStackTrace();
        }
    }

    public static class InputStreamConsumer implements Runnable {

        private InputStream is;

        public InputStreamConsumer(InputStream is) {
            this.is = is;
        }

        public InputStream getInputStream() {
            return is;
        }

        public static void consume(InputStream is) {
            InputStreamConsumer consumer = new InputStreamConsumer(is);
            Thread t = new Thread(consumer);
            t.start();
        }

        @Override
        public void run() {
            InputStream is = getInputStream();
            int in = -1;
            try {
                while ((in = is.read()) != -1) {
                    System.out.print((char)in);
                }
            } catch (IOException exp) {
                exp.printStackTrace();
            }
        }

    }
}

作为使用 ProcessBuilder pb = new ProcessBuilder("java", "-cp", "./src", "HelloWorld"); 的替代方案,您实际上可以使用...

ProcessBuilder pb = new ProcessBuilder("java", "HelloWorld");
pb.directory(new File("src"));
pb.redirectError();
Process p = pb.start();

这将在src 目录的上下文中启动java 进程

【讨论】:

    猜你喜欢
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多