我正在尝试编写一个带有接口(interface)的java程序,该接口(interface)允许用户创建.java文件并编译和运行它(本质上是一个非常简单的IDE)。我使用 java swing 作为 gui,到目前为止已经能够将接口(interface)内的 .java 文件编译为 .class 文件。我一直在研究如何从 java 代码中运行 .class 文件,但发现了很多我无法使用的答案。下面是相关编译代码:
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 文件并在代码中捕获其输出?
最佳答案
编译完成后,您需要加载 Class
对象,然后调用 main(String[])
方法。要捕获标准输出,您需要使用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 代码中运行已编译的 java .class 文件并捕获输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30430056/