Implement a static premain
(as an analogy to main
) method, like this:
import java.lang.instrument.Instrumentation;
class Example {
public static void premain(String args, Instrumentation inst) {
...
}
}
Create a manifest file (say, manifest.txt
) marking this class for pre-main execution. Its contents are:
Premain-Class: Example
Compile the class and package this class into a JAR
archive:
javac Example.java
jar cmf manifest.txt yourAwesomeAgent.jar *.class
Execute your JVM with -javaagent
parameter, like this:
java -javaagent:yourAwesomeAgent.jar -jar yourApp.jar
-javaagent
参数必须在 -jar
参数之前设置,这一点非常重要。 - berezovskyiExample
类中提供一个空的main
方法,否则可能会抛出关于缺少主要方法的错误。 - Searene以下是关于第二点所述的Java代理程序的一些有用资源。