Java字节码instrument研究

本文介绍了一个名为MyAgent的Java Agent项目,通过使用Javassist等工具实现了对特定类的方法进行耗时监控的功能。文章展示了如何配置Maven项目并利用ClassFileTransformer来修改字节码,以实现方法执行前后的时间记录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MyAgent项目

<?xml version="1.0" encoding="UTF-8"?>
<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.book.MyAgent</groupId>
    <artifactId>MyAgent</artifactId>
    <version>1.0</version>

    <dependencies>
        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.12.1.GA</version>
        </dependency>
        <dependency>
            <groupId>org.ow2.asm</groupId>
            <artifactId>asm-all</artifactId>
            <version>5.1</version>
        </dependency>
        <dependency>
            <groupId>net.bytebuddy</groupId>
            <artifactId>byte-buddy</artifactId>
            <version>1.5.7</version>
        </dependency>
        <dependency>
            <groupId>net.bytebuddy</groupId>
            <artifactId>byte-buddy-agent</artifactId>
            <version>1.5.7</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>3.0.1</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>jar-no-fork</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifestFile>src/main/resources/META-INF/MANIFEST.MF</manifestFile>
                    </archive>
                </configuration>
                <executions>
                    <execution>
                        <id>assemble-all</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <artifactSet>
                        <includes>
                            <include>javassist:javassist:jar:</include>
                            <include>net.bytebuddy:byte-buddy:jar:</include>
                            <include>net.bytebuddy:byte-buddy-agent:jar:</include>
                        </includes>
                    </artifactSet>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>${basedir}/src/main/resources</directory>
            </resource>
            <resource>
                <directory>${basedir}/src/main/java</directory>
            </resource>
        </resources>
    </build>
</project>

 

AgentTime类

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;


public class AgentTime {
    public static void premain(String agentArgs, Instrumentation inst) {
        System.out.println("监控耗时 >>>");
        // 添加 Transformer
        ClassFileTransformer transformer = new PerformMonitorTransformer();
        inst.addTransformer(transformer);
        System.out.println("监控耗时 <<<");
    }
}

PerformMonitorTransformer类

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtBehavior;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.expr.ExprEditor;
import javassist.expr.MethodCall;

public class PerformMonitorTransformer implements ClassFileTransformer {

    private static final Set<String> classNameSet = new HashSet<>();

    static {
        classNameSet.add("com.book.test.TestTime");
    }

    @Override
    public byte[] transform(ClassLoader loader,
            String className,
            Class<?> classBeingRedefined,
            ProtectionDomain protectionDomain,
            byte[] classfileBuffer) throws IllegalClassFormatException {
        //System.out.println("监控耗时 >>>1");
        try {
            String currentClassName = className.replaceAll("/", ".");
            if (!classNameSet.contains(currentClassName)) { // 仅仅提升Set中含有的类
                return null;
            }
            System.out.println("transform: [" + currentClassName + "]");

            CtClass ctClass = ClassPool.getDefault().get(currentClassName);

            CtBehavior[] methods = ctClass.getDeclaredBehaviors();

            for (CtBehavior method : methods) {
                System.out.println("method: [" + method + "]");
                enhanceMethod(method);
            }
            
            CtMethod m = ctClass.getDeclaredMethod("fun1");
            m.insertBefore("{ System.out.println($1); System.out.println($2); }");           
            return ctClass.toBytecode();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void enhanceMethod(CtBehavior method) throws Exception {
        if (method.isEmpty()) {
            return;
        }
        
        String methodName = method.getName();
        if (methodName.equalsIgnoreCase("main")) { // 不提升main方法
            return;
        }
        
        CtClass[] prams = method.getParameterTypes();
        if (prams.length > 0) {
            method.insertBefore("{ System.out.println($1);System.out.println($2); }");
        }
        
        final StringBuilder source = new StringBuilder();
        if (methodName.equalsIgnoreCase("fun3")) { // 修改fun3方法
            source.append("{")
                    .append("System.out.println(\"方法三真的被替换了\");").append("\n")
                    .append("}");
        } else {
            source.append("{")
                    .append("long start = System.nanoTime();\n") // 前置增强: 打入时间戳
                    .append("$_ = $proceed($$);\n") // 保留原有的代码处理逻辑                  
                    .append("System.out.print(\"method:[" + methodName + ">>>]\");").append("\n")
                    .append("System.out.println(\" cost:[\" +(System.nanoTime() -start)+ \"ns]\");") // 后置增强
                    .append("}");
        }

        ExprEditor editor = new ExprEditor() {
            @Override
            public void edit(MethodCall methodCall) throws CannotCompileException {
                methodCall.replace(source.toString());
            }
        };
        method.instrument(editor);
    }
}

被增强的项目:

TestAgent

<?xml version="1.0" encoding="UTF-8"?>
<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.book</groupId>
    <artifactId>TestAgent</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <build>
        <plugins>
            <plugin>    
                <artifactId>maven-assembly-plugin</artifactId>    
                <configuration>    
                    <appendAssemblyId>false</appendAssemblyId>    
                    <descriptorRefs>    
                        <descriptorRef>jar-with-dependencies</descriptorRef>    
                    </descriptorRefs>    
                    <archive>    
                        <manifest>    
                            <mainClass>com.book.test.TestTime</mainClass>    
                        </manifest>    
                    </archive>
                </configuration>    
                <executions>    
                    <execution>    
                        <id>make-assembly</id>    
                        <phase>package</phase>    
                        <goals>    
                            <goal>assembly</goal>    
                        </goals>    
                    </execution>    
                </executions>    
            </plugin>            
        </plugins>
    </build>
</project>

 TestTime类

public class TestTime {
    private int fun1(int a,int b) {
        System.out.println("\n方法一开始>>>");
        return a+b;
    }

    private void fun2() {
        System.out.println("\n方法二开始>>>");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace(); 
        }
        System.out.println("方法二结束<<<");
    }

    private void fun3() {
        System.out.println("方法三会被干掉么?");        
    }
    
    public static void main(String[] args) {
        TestTime test = new TestTime();
        test.fun1(2,3);
        test.fun2();
        test.fun3();
    }
}

运行:

java  -javaagent:E:\worktest\MyAgent\target\MyAgent-1.0-jar-with-dependencies.jar -jar E:\worktest\TestAgent\target\TestAgent-1.0-SNAPSHOT.jar com.book.test.TestTime

 

参考:https://blog.youkuaiyun.com/f59130/article/details/78481594

Javassist 使用指南(三)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值