-javaagent:
is introduced in JDK 5, and it may be late to talk about any new features in JDK 5, while JDK 6 is just around the corner. I started to use it recently but at first couldn't find any good documentation on this option.java -help
shows a brief message:-javaagent:<jarpath>[=<options>]JDK tools doc page doesn't give much more info. The official one is at the Javadoc page for java.lang.instrument, as suggested by
load Java programming language agent, see java.lang.instrument
java -help
Here is my quick summary with comments:
1. An agent is just an interceptor in front of your main method, executed in the same JVM and loaded by the same system classloader, and governed by the same security policy and context.
The name is misleading, since the word agent usually suggests something working remotely and separately from the primary entity. But it turns out the java agent as used in
-javaagent:
is much simpler than that.How to write a java agent? Just implement this method:
public static void premain(String agentArgs, Instrumentation inst);2. Agent classes must be packaged in jar file format whose META-INF/MANIFEST.MF contains at least one additional attribute:
Premain-Class
. An example of MANIFEST.MF:Manifest-Version: 1.0Once you have the custom MANIFEST.MF file, run
Premain-Class: javahowto.JavaAgent
Created-By: 1.6.0_06 (Sun Microsystems Inc.)
jar
command with cvfm
option to create the agent jar:/projects/Hello/build/classes $3. All these agent jars are automatically appended to the classpath. So no need to add them to classpath, unless you want to reorder classpath elements.
jar cvfm ../../myagent.jar ../../mymanifest.mf javahowto/MyAgent.class
4. One java application may have any number of agents by using
-javaagent:
option any number of times. Agents are invoked in the same order as specified in options.5. Each agent may also take String-valued args. I guess that's the reason why we have to use this option multiple times for multiple agents. Otherwise, we could've just done something like:
-javaagent agent1.jar:agent2.jar
, which is incorrect.6. It's convenient for java application integration. Now I can enhance/modify the behavior of an application without changing its source code.
7. JavaEE 5 has many similar construts, such as interceptors in EJB 3, and EntityListener in Java Persistence API. In JavaEE, they are managed by some sort of containers, so their semantics is much richer than javaagent.
Tags: