Text content
1. Define a Java class in memory
2. How to use HSDB and precautions
3. Decompilation of java classes
foreword
As we all know, the original bytecode data of java classes are generally stored on disk. After the file is loaded into the memory, the bytecode array can be converted into a java class through the DefineClass of the ClassLoader class, so it is also possible to directly define a java class by defining a byte array in the memory. For example, if we want to learn more about the mechanism of java dynamic proxy, the best way is to read the source code of the dynamically generated target class, but how to get its source code. The dynamic proxy class can save the bytecode of the class by setting the system property sun.misc.ProxyGenerator.saveGeneratedFiles, but this is not universal. For a class defined from a class file, if you want to view its source code, you can obtain the source code of a class file through decompilation; for a class defined from a memory array, if you want to view its source code , you first need to output the class bytecode data in the memory to a file , and then obtain the source code according to the class file , because the decompilation tool needs to receive the input of the file. We can understand this process through Demo.
1. Define a java class in memory
First obtain the DefineClass method of the ClassLoader class through reflection, and then call the method to define the class through reflection
2. How to use HSDB and precautions
HSDB is a jar package file under the jdk installation directory. The file is located under the jdk installation directory\lib. It exists in the form of an independent process and can obtain java runtime information outside the java process in a non-intrusive manner.
You can start the monitoring process on the command line java -cp sa-jdi.jar sun.jvm.hotspot.HSDB java process id
It should be noted that administrator privileges are required to run on the command line, and the java process id can be found through jps
An error will be reported when starting as a non-administrator
start as administrator
After successfully attaching to the java process, the home page will list all java processes, which can be viewed by clicking the menu tools => class browser
All classes loaded
XBootMain is defined by us directly using ClassLoader's defineClass
Click on the XBootMain class information above, and the hyperlink to create the class file is displayed in the lower area
Click the "Create .class File" link, and the XBootMain.class class file will be generated in the same directory as sa-jdi.jar
3. Decompilation of java classes
You can use java-decompiler.jar to decompile java class files, the command is
It can be seen that after the decompilation is completed, a java file is generated in the same directory