添加代理jar包就不多说了,搜到这个问题,前面的步骤都搞定了。
一、代理类的入口
public class MainAgent {
public static void agentmain(String args, Instrumentation inst) {
premain(args, inst);
}
public static void premain(String args, Instrumentation inst) {
inst.addTransformer(hotSwapTransformer);
}
}
二、hotSwapTransformer
jvm启动的时候,会加载所有的类,每一个类加载的时候都会触发一次hotSwapTransformer中的transform方法。
我们在transfrom方法中用if判断要监听的类。
比如我要修改mybatis中的org.apache.ibatis.session.Configuration的内部类StrictMap
应该监听org/apache/ibatis.session/Configuration$StrictMap
public class HotSwapTransformer implements ClassFileTransformer {
private Set<ClassFileTransformer> classFileTransformerSet = new HashSet<>();
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) {
if(MyBatisInit.XML_CONFIG_BUILDER.replace(".", "/").equals(className) ||
MyBatisInit.CONFIGURATION.replace(".", "/").equals(className)){
try {
CtClass ctClass = createCtClass(classfileBuffer, loader);
ClassPool classPool = new ClassPool();
classPool.appendSystemPath();
classPool.appendClassPath(new LoaderClassPath(loader));
if(MyBatisInit.XML_CONFIG_BUILDER.replace(".", "/").equals(className)){
MyBatisInit.modifyXMLConfigBuilder(ctClass, classPool);
}else{
MyBatisInit.modifyConfiguration(ctClass, classPool);
}
return ctClass.toBytecode();
} catch (IOException | CannotCompileException | NotFoundException e) {
e.printStackTrace();
}
}
return new byte[0];
}
public void registerTransFormer(ClassFileTransformer classFileTransformer){
classFileTransformerSet.add(classFileTransformer);
}
/**
* 创建CtClass
*/
private static CtClass createCtClass(byte[] bytes, ClassLoader classLoader) throws IOException {
ClassPool cp = new ClassPool();
cp.appendSystemPath();
cp.appendClassPath(new LoaderClassPath(classLoader));
return cp.makeClass(new ByteArrayInputStream(bytes));
}
}