I. overview
Java Agent is introduced from JDK 1.5 and later. Its function is equivalent to an interceptor before your main function, that is, before executing the main function, execute the code in the Agent first.
The Agent code runs in the same JVM as your main method and is loaded by the same classloader and managed by the same security policy and context.
2. Simply write an Agent
1. Write a Java class, including any of the following two methods:
public static void premain(String agentArgs, Instrumentation inst); //[1] public static void premain(String agentArgs); //[2]
When [1] and [2] exist at the same time, [1] will be executed first, and [2] will be ignored.
The specific code is as follows:
import java.lang.instrument.Instrumentation; public class MyAgent { public static void premain(String agentArgs, Instrumentation inst) { System.out.println("this is an agent."); System.out.println("args:" + agentArgs + "\n"); } }
2. jar packaging
First, you need to add the META-INF/MANIFEST.MF file in the resources directory of the code. Its purpose is to specify the class of premain class.
Manifest-Version: 1.0 Premain-Class: agent.MyAgent Can-Redefine-Classes: true
Secondly, configure the relevant configuration of packaging in pom.xml.
<packaging>jar</packaging> <build> <finalName>my-agent</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.3.2</version> <configuration> <archive> <index>true</index> <manifestFile> src/main/resources/META-INF/MANIFEST.MF </manifestFile> <manifest> <addDefaultImplementationEntries/> </manifest> </archive> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins> </build>
Finally, execute mvn clean package to generate a my-agent.jar.
3. Agent operation
Run the Agent with the following settings.
-javaagent: file location [= parameter]
Note: if multiple agents are running, list them. -Javaagent: file location [= parameter] - javaagent: file location [= parameter], where the parameter is agentArgs in the premain function.
III. Agent use
First, create a new test class. As follows:
public class AgentTest { public static void main(String[] args) { System.out.println("this is main"); } }
Command line running: java -javaagent: file location [= parameter]
Idea running: in idea, configure as follows.
The result is as follows: I loaded the Agent twice, but the parameters passed in are different.
this is an agent. args:first this is an agent. args:second this is main