HotSwapper热加载
public class HotSwapperTest {public static void main(String[] args) throws NotFoundException, CannotCompileException, IOException, IllegalConnectorArgumentsException {Person person = new Person();System.out.println(Person.class.getClassLoader());new Thread(() -> {System.out.println(Person.class.getClassLoader());while (true){person.foo();try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}}}).start();ClassPool classPool = ClassPool.getDefault();System.out.println(classPool.getClassLoader());CtClass ctClass = classPool.get(person.getClass().getName());CtMethod ctMethod = ctClass.getDeclaredMethod("foo");ctMethod.setBody("System.out.println(\"change\");");HotSwapper hs = new HotSwapper(8000);hs.reload(person.getClass().getName(), ctClass.toBytecode());}
}
javassist.tools.HotSwapper
,是 javassist
的包中提供的热加载替换类操作。在执行时需要启用 JPDA
(Java平台调试器体系结构)。
最后使用 hs.reload 执行热加载替换操作,这里的 ctClass.toBytecode() 获取的是处理后类的字节码。
引用 tools.jar
pom.xml:
<dependency><groupId>com.sungroupId><artifactId>toolsartifactId><version>1.4.2version><scope>systemscope><systemPath>${java.home}/../lib/tools.jarsystemPath>
dependency>
配置-agentlib
启动HotSwapperTest 的 VM options 添加配置项
-agentlib:jdwp&#61;transport&#61;dt_socket,server&#61;y,suspend&#61;n,address&#61;8000
用于启用 JPDA&#xff08;Java平台调试器体系结构&#xff09;
。
运行结果
Listening for transport dt_socket at address: 8000
sun.misc.Launcher$AppClassLoader&#64;18b4aac2
sun.misc.Launcher$AppClassLoader&#64;18b4aac2
foo
sun.misc.Launcher$AppClassLoader&#64;18b4aac2
foo
foo
foo
foo
foo
change
change
结果看出&#xff0c;主线程、子线程、Javassist默认的 ClassLoader
都是 AppClassLoader
。
重写方法后&#xff0c;hs.reload 执行热加载替换操作&#xff0c;后续 foo 方法执行体改变。
https://www.dandelioncloud.cn/article/details/1466967080951181313
http://events.jianshu.io/p/041a42d9ca66
https://blog.csdn.net/H291850336/article/details/103187408
https://blog.csdn.net/jiangguilong2000/article/details/73924206
https://blog.csdn.net/blueheartstone/article/details/113512479
http://www.360doc.com/content/21/1213/11/78097014_1008492520.shtml