从Java代码中运行已编译的Java .class文件并捕获输出 [英] Running a compiled java .class file from within java code and capturing output

查看:64
本文介绍了从Java代码中运行已编译的Java .class文件并捕获输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个带有接口的Java程序,该接口允许用户创建.java文件并进行编译和运行(本质上是一个非常简单的IDE).我正在使用Java swing作为gui,到目前为止,已经能够将接口中的.java文件编译为.class文件.我一直在研究如何从Java代码中运行.class文件,但发现了很多无法解决的答案.以下是相关的编译代码:

I'm trying to write a java program with an interface that allows the user to create .java file and compile and run it (essentially a very simplistic IDE). I'm using java swing for the gui and have so far been able to compile a .java file from within the interface into a .class file. I've been researching how to run a .class file from within java code but have found a wide range of answers which I haven't been able to get working. Here is the relevant code for compilation:

File javaFile = new File( "test1.java" );
String code = entry.getText(); // get text entered by user in GUI
try{
  PrintWriter writer = new PrintWriter( javaFile );  // write text to .java file  
  writer.print( code );
  writer.close();
}
catch( FileNotFoundException e ){
  System.err.println( e );
}
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
List<File> sourceFileList = new ArrayList<File>();
sourceFileList.add( javaFile );
StandardJavaFileManager fileManager = compiler.getStandardFileManager( null, null, null );
Iterable<? extends JavaFileObject> javaSource = fileManager.getJavaFileObjectsFromFiles( sourceFileList );
CompilationTask task = compiler.getTask(null, fileManager, null, null, null, javaSource);
task.call(); // compile .java file into .class file

如何运行已编译的.class文件并在代码中捕获其输出?

How can I run a compiled .class file and capture its output within my code?

推荐答案

编译后,您将需要加载 Class 对象,然后调用 main(String [])方法.要捕获标准输出,您将需要使用 System.setOut .

Once it's compiled, you will need to load the Class object and then invoke the main(String[]) method. To capture the stdout, you will need to use System.setOut.

private String invokeClass(String className) throws URISyntaxException, IOException, ReflectiveOperationException {
    Class<?> clazz = Class.forName(className);
    // Alternatively, you can load the new class with a new Classloader, if you don't want to pollute the current Classloader
    // Class<?> clazz = new URLClassLoader(new URL[]{getClass().getClassLoader().getResource("").toURI().toURL()}, getClass().getClassLoader()).loadClass(className);
    Method main = clazz.getDeclaredMethod("main", String[].class);
    try ( ByteArrayOutputStream out = new ByteArrayOutputStream();
          PrintStream ps = new PrintStream(out)) {
        System.setOut(ps);
        main.invoke(main, new Object[]{new String[0]});
        return out.toString();
    }
    finally {
        // Reset to the console
        System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
    }
}

这篇关于从Java代码中运行已编译的Java .class文件并捕获输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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