将java对象写入类文件 [英] write java object into class file

查看:192
本文介绍了将java对象写入类文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将加载的Java对象写入 .class 文件,或者是否可以轻松读取任何其他类型的文件来表示实例的属性。

Is there any way to write a loaded Java object into a .class file or is there any other type of file that can easily be read to represent an instance's properties.

例如,CGLIB将创建一个扩展另一个的代理bean,我真的想将这个增强的bean导出到文件看看它是如何被增强的。

For example, CGLIB will create an proxy bean which extends another, i really want to export this enhanced bean out to a file to see how it was enhanced.

推荐答案

对于cglib,实例只能序列化,并且只有实例的方法拦截器支持序列化。没有其他办法。

For cglib, instances can only be serialized and only if the instance's method interceptors support serialization. There is no other way.

为了获得cglib生成的类文件,你可以调用

In order to get hold of a cglib-generated class file, you can call the

void generateClass(ClassVisitor v)

方法。这个方法可以采用ASM ClassWriter ,它可以在调用方法后发出一个表示类文件的字节数组。然而,这个类文件本身对你没有多大帮助,因为cglib需要显式地初始化类,例如将回调处理程序注入到类的字段中。这是在库内完成的。但是,使用手头的类文件和调试模式自省,您可以添加这些片段并了解增强类的工作原理。

method. This method can take an ASM ClassWriter which can after calling the method emitt a byte array representing the class file. This class file by itself does however not help you much as cglib needs to initialize the class explicitly, e.g. inject the callback handlers into the class's fields. This is done inside of the library. However, with the class file at hand and with debug-mode introspection, you can add the pieces and understand how your enhanced class works.

最后,如果我可以推荐你cglib的替代方案,其中所有这些都更容易,请查看 Byte Buddy foward用于提取类文件的API,并且还提供与此类文件并行的所谓的 LoadedTypeInitializer 。后面的初始化程序包含类的任何设置逻辑,并且易于阅读。此外,他们自己可以序列化。

Finally, if I can recommend you an alternative to cglib where all this is easier, have a look at Byte Buddy which has a straight-foward API for extracting a class file and also offers so-called LoadedTypeInitializers in parallel to this class file. The latter initializers contain any setup logic for a class and are easy to read. Also, they are themselfs serializable.

这篇关于将java对象写入类文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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