write java object into class file

2019-05-23 11:17发布

问题:

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.

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.

回答1:

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.



回答2:

to use HSDB tool in JDK

  1. keep your program running
  2. run HSDB tool:

    java -classpath "$JAVA_HOME/lib/sa-jdi.jar" sun.jvm.hotspot.HSDB

  3. input the program pid

  4. choose tools and you can save .class file,that is what you want