使用 javax.tools.JavaCompiler 在内存中完全编译代码 [英] Compile code fully in memory with javax.tools.JavaCompiler

查看:49
本文介绍了使用 javax.tools.JavaCompiler 在内存中完全编译代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 javax.tools 包 (JDK 1.7) 中的 JavaCompiler 来即时编译一些东西,如下所示:

I'm using the JavaCompiler from the javax.tools package (JDK 1.7) to compile some stuff on the fly, like this:

compiler.run(null, null, "-cp", paths, "path/to/my/file.java");

它可以工作,但我想在内存中完成所有操作(例如,传递带有代码的字符串,而不是源文件,并取回字节码而不是 .class 文件).我发现扩展 InputStreamOutputStream 参数没有用,因为它可能与控制台中的相同.你知道一种让 run 方法像这样工作的方法吗?或者您是否知道使用 getTask() 方法执行此操作的确认方法?(扩展 FileManager 看起来很容易,但没那么容易 :)

It works but I would like to do it all in memory (e.g. pass a string with the code, not the source file, and get the byte code back not a .class file). I found that extending the InputStream and OutputStream parameters is no use since it's probably just the same as in the console. Do you know a way to make the run method work like this? Or do you know a confirmed way to do this with the getTask() method? (extending the FileManager looks easy but isn't that easy :)

推荐答案

我已经在 Mac OS Java 7 中运行了上述代码.它们都不起作用.所以我写了一个https://github.com/trung/InMemoryJavaCompiler

I've run the above code in Mac OS Java 7. None of them works. So i wrote one https://github.com/trung/InMemoryJavaCompiler

StringBuffer sourceCode = new StringBuffer();
sourceCode.append("package org.mdkt;
");
sourceCode.append("public class HelloClass {
");
sourceCode.append("   public String hello() { return "hello"; }");
sourceCode.append("}");

Class<?> helloClass = InMemoryJavaCompiler.compile("org.mdkt.HelloClass", sourceCode.toString());

这篇关于使用 javax.tools.JavaCompiler 在内存中完全编译代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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