1. javajaent是什么
javaagent可以理解为是一个插件,需要有一个jvm进程才能运行。例如arthas这个工具就是用到了javaagent。
2. 如何使用
1. 一种调用方式:java -javaagent:path[=参数=参数值]
2. 方法签名
public static void premain(String args, Instrumentation inst) {
}
public static void agentmain(String args, Instrumentation inst) {
}
看到签名就应该能够猜到,一个是在main函数之前运行的;一个是attach到jvm进程之后运行的。
3. premain的案例
新建一个maven工程
1. pom文件
<?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.lagou</groupId>
<artifactId>ljavaagent</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<!-- <version>2.2-beta-5</version>-->
<configuration>
<descriptorRefs>
<descriptorRef>
jar-with-dependencies
</descriptorRef>
</descriptorRefs>
<archive>
<manifestFile>
src/main/resources/META-INF/MANIFEST.MF
</manifestFile>
</archive>
</configuration>
<executions>
<execution>
<goals>
<goal>attached</goal>
</goals>
<phase>package</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
2. MANIFEST.MF文件
Manifest-Version: 1.0
Premain-Class: com.lagou.SimpleAgent
Agent-Class: com.lagou.SimpleAgent
Can-Redefine-Classes: true
Can-Retransform-Classes: true
3. 类
package com.lagou;
import java.lang.instrument.Instrumentation;
public class SimpleAgent {
public static void premain(String args, Instrumentation inst) {
System.out.println("args:" + args);
System.out.println("instrumentation: " + inst);
System.out.println(SimpleAgent.class.getSimpleName() + "public static void premain(String args, Instrumentation inst)");
}
public static void agentmain(String args, Instrumentation inst) {
System.out.println("args:" + args);
System.out.println("instrumentation: " + inst);
System.out.println(SimpleAgent.class.getSimpleName() + "public static void agentmain(String args, Instrumentation inst)");
}
}
4. 编译
使用
~/software/arthas/ java -javaagent:/Users/lixi/ljavaagent/target/ljavaagent-1.0-SNAPSHOT-jar-with-dependencies.jar=args=tom -jar math-game.jar
args:args=tom
instrumentation: sun.instrument.InstrumentationImpl@33909752
SimpleAgentpublic static void premain(String args, Instrumentation inst)
135397=71*1907
75004=2*2*17*1103
illegalArgumentCount: 1, number is: -148459, need >= 2 ~/software/arthas/