BilboDai BilboDai - 1 year ago 108
Java Question

write java object into class file

Is there any way to write a loaded Java object into a

file or is there any other type of file that can easily be read to represent an instance's properties.

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

Answer Source

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

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

void generateClass(ClassVisitor v)

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.

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download