以下是实现Java Agent进行方法插桩和性能统计的完整方案,包含多个关键组件:
import java.lang.instrument.Instrumentation;
public class AgentMain {
public static void premain(String args, Instrumentation inst) {
inst.addTransformer(new MethodTimerTransformer());
}
}
java.lang.instrument.ClassFileTransformer;
import java.security.ProtectionDomain;
import javassist.*;
public class MethodTimerTransformer implements ClassFileTransformer {
@Override
public byte[] transform(ClassLoader loader, String className,
Class> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] classfileBuffer) {
try {
ClassPool pool = ClassPool.getDefault();
CtClass ctClass = pool.get(className.replace('/', '.'));
for (CtMethod method : ctClass.getDeclaredMethods()) {
method.addLocalVariable("startTime", CtClass.longType);
method.insertBefore("startTime = System.nanoTime();");
method.insertAfter("System.out.println(\"Method " + method.getName() +
" executed in \" + (System.nanoTime() - startTime) + \" ns\");");
}
return ctClass.toBytecode();
} catch (Exception e) {
return null;
}
}
}
ifest-Version: 1.0
Premain-Class: AgentMain
Can-Redefine-Classes: true
Can-Retransform-Classes: true
使用说明:1. 打包成agent.jar 2. 启动应用时添加-javaagent .jar参数 3. 运行时将输出所有方法的执行时间。该方案通过Javassist实现动态字节码修改,在方法前后插入计时逻辑,适用于性能分析和调优场景。
http://www.thedesignrepublic.com/
http://www.yxhgq.com/
http://www.jianhuotech.com/
http://www.bjyozd.com
http://www.sunny-way.cn/
http://www.cnsenkai.com/
http://www.zluren.com.cn/
http://www.cddtk119.com/
http://www.boao168.com.cn/
http://www.czs365.net/
http://www.ianvan.com/
http://www.fangzhoushidai.com
http://www.qiaosen-kj.com
http://gzhyxjj.cn
http://xatlzg.com
http://www.doushiwang.cn
http://www.sxyuanzheng.com
http://www.jwdyd.com
http://www.xaminglang.com
http://www.lboneti.cn
http://www.ahlongda.com
http://www.gdlanye.com
http://www.ktlcutter.com
http://www.hbzfjn.com
http://www.shbaimule.com
http://www.clgzkj.com
http://www.fjjhwy.cn
http://www.goodluck-lift.com
http://www.storlead.shop
http://magicians.com.cn
http://mall.yeepayer.com
http://tzkqzj.com
http://www.jinfanweilai.com
https://www.durkflex.cn/
http://www.szfmhj168.com.cn/
http://hfnz.ahaiba.com/
http://sjmzjypx010.ahaiba.com/
http://nyh.ahaiba.com/
http://thszsgs.com/