Change the object creation behavior so that they can use the class loaded by the custom classloader during creation.
Implementation of custom Loaders
The custom loader still needs to perform the class loading function. There is a problem here. The same class loader cannot load two classes with the same name at the same time. The generated class name will not change regardless of the class structure, the classloader can only destroy loaded classes before the VM is stopped, so that the classloader cannot load the updated classes. Here is a tip to save each loaded class as a class with version information, such as loading Test. the class stored in the memory is Test_v1.class. When the class changes, the reloaded class name is Test_v2.class. However, the defineClass method that truly loads the class file to create the class is a native method, and it becomes very difficult to modify it. Therefore, there is only one path left in front, that is, to directly modify the compiled class file.
Use ASM to modify the class file
There are many frameworks that can modify bytecode, such as ASM and CGLIB. This document uses ASM. First, we will introduce the structure of the class file. The class file contains the following types of information: basic information about the class, including access permission information, class Name Information, and parent class information, interface Information. The second is the class variable information. The third is the method information. ASM loads a class file first, and then reads the information of the class in strict sequence. You can define the enhancement component as needed to modify the information, and finally output it into a new class.
First, let's take a look at how to use ASM to modify class information.
Listing 1. Using ASM to modify bytecode
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); ClassReader cr = null; String enhancedClassName = classSource.getEnhancedName(); try { cr = new ClassReader(new FileInputStream( classSource.getFile())); } catch (IOException e) { e.printStackTrace(); return null; } ClassVisitor cv = new EnhancedModifier(cw, className.replace(".", "/"), enhancedClassName.replace(".", "/")); cr.accept(cv, 0);
The process for ASM to modify the bytecode file is a chain of responsibility mode. First, a ClassReader is used to read the bytecode, then ClassVisitor is used for personalized modification, and finally the modified bytecode is output using ClassWriter.
As mentioned earlier, you need to modify the class Name of the read class file and load it into a derived class with a new name. There are two steps.
Step 1: first convert the original class into an interface.
Listing 2. redefinition of the original Class
public Class
redefineClass(String className){ ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); ClassReader cr = null; ClassSource cs = classFiles.get(className); if(cs==null){ return null; } try { cr = new ClassReader(new FileInputStream(cs.getFile())); } catch (IOException e) { e.printStackTrace(); return null; } ClassModifier cm = new ClassModifier(cw); cr.accept(cm, 0); byte[] code = cw.toByteArray(); return defineClass(className, code, 0, code.length); }
First load the class file of the original class. An enhancement component is defined here.ClassModifierModifies the type of the original class and converts it to an interface. All method logic of the original class will be removed.
Step 2: The generated Derived classes implement this interface, that is, the original class, and copy all the method logic in the original class. If the class needs to be updated, a new derived class will be generated and this interface will be implemented. The purpose of this operation is that, no matter how it is modified, the derived classes of the same class have a common interface, and the conversions between them become non-transparent.
Listing 3. Define a derived class
// Re-define this class private Class when the class file changes
RedefineClass (String className, ClassSource classSource) {ClassWriter cw = new ClassWriter (ClassWriter. COMPUTE_MAXS); ClassReader cr = null; classSource. update (); String enhancedClassName = classSource. getEnhancedName (); try {cr = new ClassReader (new FileInputStream (classSource. getFile ();} catch (IOException e) {e. printStackTrace (); return null;} EnhancedModifier em = new EnhancedModifier (cw, className. replace (". ","/"), enhancedClassName. replace (". ","/"); ExtendModifier exm = new ExtendModifier (em, className. replace (". ","/"), enhancedClassName. replace (". ","/"); cr. accept (exm, 0); byte [] code = cw. toByteArray (); classSource. setByteCopy (code); Class
Clazz = defineClass (enhancedClassName, code, 0, code. length); classSource. setClassCopy (clazz); return clazz ;}
Load the class file of the original class again. Two enhancement components are defined here. One isEnhancedModifierThe role of this enhancement component is to change the original class name. The second enhancement component isExtendModifierThe purpose of this enhancement component is to change the parent class of the original class so that the modified derived class can implement the same original class (the original class has been converted into an interface at this time ).
Another function of the custom classloader is to monitor the class files that will change. The classloader manages a timer and regularly scans for changes to these class files.
Change the object creation behavior
There are two common methods for creating objects in Java virtual machines: static creation, new object, dynamic creation, and object creation through reflection.
Since the type of the original class has been changed in the User-Defined loader and it has been changed from class to interface, neither of the two creation methods can be established. What we need to do is to convert the behavior of instantiating the original class into instantiating the derived class.
For the first method, you need to change static creation to getting the class through classloader, and then dynamically create the object.
Listing 4. logic of the replaced Instruction Set
// Original logic Greeter p = new Greeter (); // The changed logic IGreeter p = (IGreeter) MyClassLoader. getInstance (). findClass ("com. example. greeter "). newInstance ();
Here we need to use ASM to modify the class file. Find all new object statements, replace them with the form of classloader to get the object.
Listing 5. Using ASM to modify the method body
@ Override public void visitTypeInsn (int opcode, String type) {if (opcode = Opcodes. NEW & type. equals (className) {List
Variables = node. localVariables; String compileType = null; for (int I = 0; I
For the second method, you need to modifyClass.forName()AndClassLoader.findClass()So that they can load classes through the custom loader.
Use Java agent to intercept the default loader Behavior
The previously implemented class loader has solved the features required for hot deployment. However, when the JVM is started, it does not use a custom loader to load all class files under the classpath, instead, it is loaded by the Application Loader. If you use a custom loader to reload the loaded class, a LinkageError exception may occur. Therefore, you must replace the loaded class before starting the application. If only one method can be used before jdk1.4, The classloader loading behavior in jdk is changed so that it directs to the loading behavior of the custom loader. Fortunately, after JDK, we have another method that is more aggressive and smaller. This is the JavaAgent method. After JVM is started, the Java agent can provide a short gap before the application is started, provide space for users to perform some special actions. A common application is to use Java agent for Aspect-Oriented Programming and add monitoring logs among methods.
Java agent is easy to implement. You only need to define a premain method in a class.
Listing 6. A simple JavaAgent
public class ReloadAgent { public static void premain(String agentArgs, Instrumentation inst){ GeneralTransformer trans = new GeneralTransformer(); inst.addTransformer(trans); } }
Then write a manifest filePremain-ClassAttribute to define an ownerpremainMethod class name.
Generate a jar package containing the manifest file.
manifest-Version: 1.0 Premain-Class: com.example.ReloadAgent Can-Redefine-Classes: true
Finally, you need to add-javaagentParameter, add this jar. You can alsoJavaagentAdd the parameter, which is the absolute path of the test project in the test code. In this way, before the application is executedpremainMethod, and pre-parse the class to be loaded.
Figure 1. Add execution Parameters
Here we useJavaAgentReplace the original bytecode to prevent the original bytecode from being loaded by the Java Virtual Machine. You only need to implementOne ClassFileTransformerTo replace the class.
Listing 7. Replacing class
@Override public byte [] transform(ClassLoader paramClassLoader, String paramString, Class
paramClass, ProtectionDomain paramProtectionDomain, byte [] paramArrayOfByte) throws IllegalClassFormatException { String className = paramString.replace("/", "."); if(className.equals("com.example.Test")){ MyClassLoader cl = MyClassLoader.getInstance(); cl.defineReference(className, "com.example.Greeter"); return cl.getByteCode(className); }else if(className.equals("com.example.Greeter")){ MyClassLoader cl = MyClassLoader.getInstance(); cl.redefineClass(className); return cl.getByteCode(className); } return null; }
So far, all the work has been done. Let's take a look at the hotswap results.
Figure 2. Test execution result
Conclusion
Solving hotswap is a difficult topic. This article only solves the problem of using new logic for newly instantiated objects and does not change the behavior of instantiated objects, if the JVM can re-design the class lifecycle and update a class at runtime, hotswap will become a new feature of Java. The official JVM has not been able to solve the hot deployment problem. It may also be because it cannot completely overcome many of the difficulties. We hope that Jdk will solve this problem in the future and make Java applications more friendly to updates, avoid wasting time restarting applications.