Recently, I am learning JavaAgent. Let me talk about my learning experience.

JavaAgent a technology used to modify bytecode when loading a class.Copy the code

The principle:

JavaAgent, introduced after jdk1.5, is a JAVA agent technology that uses ASM to dynamically modify the loaded class binary file when the JVM loads it.

To create the agent

First step: Create a class and create two methods

import java.lang.instrument.Instrumentation; /** * @author fade * @Title: MyAgent * @ProjectName my-agent * @Description: TODO * @date 2021/4/123:51 PM */ public class MyAgent {/** * Runs in the same JVM as the main method * is loaded by the same System ClassLoader * is managed by the same security policy and context * * @param agentOps * @param Inst * @author fade * @create 2021/4/123:51 PM */ public static void premain(String agentOps, Instrumentation inst) {System. Out. Println (" = = = = = = = = = premain method performs = = = = = = = = "); System.out.println(agentOps); } /** * If there is no premain(String agentOps, Instrumentation inst) * then premain(String agentOps) * * @param agentOps * @author fade * @create 2021/4/123:51 PM */ Public static void premain(String agentOps) {system.out.println ("=========premain method 2========"); System.out.println(agentOps); }}Copy the code

public static void agentmain(String args, Instrumentation inst)

Public static void agentMain (String args)

Methods. And when both exist, the former takes precedence. Args and inst are the same as in Premain.

Step 2: First method (Maven method) poM file add:

<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
        <archive>
            <manifestEntries>
                <Premain-Class>com.sage.agent.MyAgent</Premain-Class>
                <Agent-Class>com.sage.agent.MyAgent</Agent-Class>
                <Can-Redefine-Classes>true</Can-Redefine-Classes>
                <Can-Retransform-Classes>true</Can-Retransform-Classes>
            </manifestEntries>
        </archive>
    </configuration>
</plugin>
Copy the code

Premain-class and agent-class point to the main Class of the Agent, that is, MyAgent.

Create a MANNIFEST.MF file in the resource and specify agent-class:

Manifest-version: 1.0 agent-class: com.sage. Agent.MyAgent Created-By: 1.6.0_29Copy the code

A simple agent is implemented

How do I load the Java Agent

Javaagent :**.jar: javaAgent :**.jar: JavaAgent :**.jar: JavaAgent :**.jar: JavaAgent :**.jar: JavaAgent :**.jar But if the Premain method fails or throws an exception, the JVM is aborted, which can be fatal.