将Class对象转换为字节 [英] convert Class object to bytes
问题描述
如果我有 Class 运行时的实例,我可以得到它的byte []表示吗?我感兴趣的字节将在类文件中格式,这样它们就是[ClassLoader.defineClass] [3]的有效输入。
[3]: http://java.sun.com/ j2se / 1.5.0 / docs / api / java / lang / ClassLoader.html#defineClass(java.lang.String ,byte [],int,int)
编辑:我接受了一个getResourceAsStream答案,因为它非常简单并且大部分时间都可以工作.ClassFileTransformer似乎是一个更强大的解决方案,因为它不需要从.class文件加载类;它会处理以网络加载的类为例。有一些箍可以通过这种方法跳过,但我会记住。谢谢大家!
您通常只需加载该类作为Classloader的资源。
Class c = ...
String className = c.getName();
String classAsPath = className.replace('。','/')+。class;
InputStream stream = c.getClassLoader()。getResourceAsStream(classAsPath);
我可能会建议使用Apache commons-io中的东西将InputStream读入 byte []
,但 IOUtils.toByteArray()
应该可以解决问题。编写代码很容易出错和/或变慢。
If I have a Class instance at runtime, can I get its byte[] representation? The bytes I'm interested in would be in the Class file format, such that they'd be valid input to [ClassLoader.defineClass][3].
[3]: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ClassLoader.html#defineClass(java.lang.String, byte[], int, int)
EDIT: I've accepted a getResourceAsStream answer, because it's very simple and will work most of the time. ClassFileTransformer seems like a more robust solution because it doesn't require that classes be loaded from .class files; it would handle network-loaded classes for example. There's a few hoops to jump through with that approach, but I'll keep in in mind. Thanks all!
You can usually just load the class as a resource from the Classloader.
Class c = ...
String className = c.getName();
String classAsPath = className.replace('.', '/') + ".class";
InputStream stream = c.getClassLoader().getResourceAsStream(classAsPath);
I would probably recommend using something from Apache commons-io to read the InputStream into a byte[]
, but IOUtils.toByteArray()
should do the trick. Writing that code is really easy to get wrong and/or make slow.
这篇关于将Class对象转换为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!