本文主要是介绍Java Instrument动态修改字节码入门-添加方法耗时监控,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
平常在统计方法执行的耗时时长时,一般都是在方法的开头和结尾通过
System.currentTimeMillis()
拿到时间,然后做差值,计算耗时,这样不得不在每个方法中都重复这样的操作,现在使用Instrument,可以优雅的实现该功能。
一、编写Agent类
package com.jdktest.instrument;import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;public class AopAgentTest {static private Instrumentation _inst = null; /** * The agent class must implement a public static premain method similar in principle to the main application entry point. * After the Java Virtual Machine (JVM) has initialized, * each premain method will be called in the order the agents were specified, * then the real application main method will be called.**/ public static void premain(String agentArgs, Instrumentation inst) { System.out.println("AopAgentTest.premain() was called."); /* Provides services that allow Java programming language agents to instrument programs running on the JVM.*/ _inst = inst; /* ClassFileTransformer : An agent provides an implementation of this interface in order to transform class files.*/ ClassFileTransformer trans = new AopAgentTransformer(); System.out.println("Adding a AopAgentTest instance to the JVM."); /*Registers the supplied transformer.*/_inst.addTransformer(trans); }
}
代码功能详见注释。
二、编写ClassFileTransformer
ClassFileTransformer
需要实现transform
方法,根据自己的功能需要修改class字节码,在修改字节码过程中需要借助javassist进行字节码编辑。
javassist是一个开源的分析、编辑和创建java字节码的类库。通过使用javassist对字节码操作可以实现动态”AOP”框架。
关于java字节码的处理,目前有很多工具,如bcel,asm(cglib只是对asm又封装了一层)。不过这些都需要直接跟虚拟机指令打交道。javassist的主要的优点,在于简单,而且快速,直接使用java编码的形式,而不需要了解虚拟机指令,就能动态改变类的结构,或者动态生成类。
package com.jdktest.instrument;import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CodeConverter;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.expr.ExprEditor;
import javassist.expr.MethodCall;public class AopAgentTransformer implements ClassFileTransformer{public byte[] transform(ClassLoader loader, String className,Class<?> classBeingRedefined, ProtectionDomain protectionDomain,byte[] classfileBuffer) throws IllegalClassFormatException {byte[] transformed = null; System.out.println("Transforming " + className); ClassPool pool = null; CtClass cl = null; try { pool = ClassPool.getDefault();cl = pool.makeClass(new java.io.ByteArrayInputStream( classfileBuffer)); // CtMethod aop_method = pool.get("com.jdktest.instrument.AopMethods").
// getDeclaredMethod("aopMethod");
// System.out.println(aop_method.getLongName());CodeConverter convert = new CodeConverter();if (cl.isInterface() == false) { CtMethod[] methods = cl.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { if (methods[i].isEmpty() == false) { AOPInsertMethod(methods[i]); } } transformed = cl.toBytecode(); } } catch (Exception e) { System.err.println("Could not instrument " + className + ", exception : " + e.getMessage()); } finally { if (cl != null) { cl.detach(); } } return transformed; }private void AOPInsertMethod(CtMethod method) throws NotFoundException,CannotCompileException {//situation 1:添加监控时间method.instrument(new ExprEditor() { public void edit(MethodCall m) throws CannotCompileException { m.replace("{ long stime = System.currentTimeMillis(); $_ = $proceed($$);System.out.println(\""+ m.getClassName() + "." + m.getMethodName()+ " cost:\" + (System.currentTimeMillis() - stime) + \" ms\");}");}}); //situation 2:在方法体前后语句
// method.insertBefore("System.out.println(\"enter method\");");
// method.insertAfter("System.out.println(\"leave method\");");}}
三、打包Agent jar包
因为agent依赖javassist,在build时需要加入<Boot-Class-Path>
,pom文件如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.jdktest</groupId><artifactId>MyInstrument</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>instrument</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>javassist</groupId><artifactId>javassist</artifactId><version>3.8.0.GA</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency></dependencies><build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.2</version> <configuration> <archive> <manifestEntries> <Premain-Class>com.jdktest.instrument.AopAgentTest</Premain-Class> <Boot-Class-Path>E:/maven-lib/javassist/javassist/3.8.0.GA/javassist-3.8.0.GA.jar</Boot-Class-Path> </manifestEntries> </archive> </configuration> </plugin> <plugin> <artifactId>maven-compiler-plugin </artifactId > <configuration> <source> 1.6 </source > <target> 1.6 </target> </configuration> </plugin> </plugins> </build>
</project>
四、需要添加耗时监控的client
随意编写需要添加耗时监控的代码并打jar包。
package com.jdktest.SayHello;public class Target {public static void main(String[] args) {new Target().sayHello();}public void sayHello(){System.out.println("Hello, guys!");}
}
如果sayHello
方法中又调用了同类中的方法或者别的类中的方法,这些被调用的方法的耗时仍可被监控到。
五、执行
在cmd下执行如下命令:
java -javaagent:E:/workspace/MyInstrument/target/MyInstrument-0.0.1-SNAPSHOT.jar -cp E:/workspace/SayHello/target/SayHello-0.0.1-SNAPSHOT.jar com.jdktest.SayHello.Target
六、执行结果
这篇关于Java Instrument动态修改字节码入门-添加方法耗时监控的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!