JavaCompiler从JDK 1.6:如何直接写类字节到byte []数组? [英] JavaCompiler from JDK 1.6: how to write class bytes directly to byte[] array?

查看:335
本文介绍了JavaCompiler从JDK 1.6:如何直接写类字节到byte []数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我最近了解到新的 JavaCompiler API 在JDK 1.6中可用。这使得直接从运行代码中编译 String .class 文件非常简单:

  String className =Foo; 
String sourceCode =...;

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

List< JavaSourceFromString> unitsToCompile = new ArrayList< JavaSourceFromString>()
{{
add(new JavaSourceFromString(className,sourceCode));
}};

StandardJavaFileManager fileManager = compiler.getStandardFileManager(null,null,null);
compiler.getTask(null,fileManager,null,null,null,unitsToCompile).call();
fileManager.close();

ByteArrayOutputStream bos = new ByteArrayOutputStream();
FileInputStream fis = new FileInputStream(className +.class);
IOUtils.copyStream(fis,bos);

return bos.toByteArray();

您可以从 JavaSourceFromString Javadoc



这将非常方便地在当前工作中编译 sourceCode Foo.class 目录。



:可以直接编译为 byte [] 数组,并避免处理 File I / O的混乱?

解决方案

也许你可以创建自己的 javax.tools.JavaFileManager 实现类,你将返回自己的实现 javax.tools.FileObject ,然后将它写出到内存,而不是磁盘。所以对于你的子类 javax.tools.FileObject Writer openWriter()throws IOException $ c> java.io.StringWriter 。所有方法都应转换为 String


So I recently learned of the new JavaCompiler API available in JDK 1.6. This makes it very simple to compile a String to a .class file directly from running code:

String className = "Foo";
String sourceCode = "...";

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

List<JavaSourceFromString> unitsToCompile = new ArrayList<JavaSourceFromString>() 
    {{ 
         add(new JavaSourceFromString(className, sourceCode)); 
    }};

StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
compiler.getTask(null, fileManager, null, null, null, unitsToCompile).call();
fileManager.close();    

ByteArrayOutputStream bos = new ByteArrayOutputStream();
FileInputStream fis = new FileInputStream(className + ".class");
IOUtils.copyStream(fis, bos);

return bos.toByteArray();

You can grab the source to JavaSourceFromString from the Javadoc.

This will very handily compile sourceCode to Foo.class in the current working directory.

My question is: is it possible to compile straight to a byte[] array, and avoid the messiness of dealing with File I/O altogether?

解决方案

Maybe you could create your own javax.tools.JavaFileManager implementing class where you would return your own implementation of javax.tools.FileObject which would then write it out to memory instead to disk. So for your subclass of javax.tools.FileObject Writer openWriter() throws IOException method you would return a java.io.StringWriter. All the methods should be converted to their String counterparts.

这篇关于JavaCompiler从JDK 1.6:如何直接写类字节到byte []数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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