Java Agent is an instrumentation API which is usually overlooked and allows you to modify bytecode at runtime. This means that is a powerful feature but “with great power there must also come great responsibility”.
The Java Agent feature was added as part of JDK 1.5 and has some use cases like metrics generation, for testing, in Aspect Oriented Programming and in any other scenario that requires modifying the bytecode at runtime.
A Java Agent is simply a class with a premain method that runs when the JVM is launched. We will show how to create a simple Java Agent in the next section.
Implementation
- Create a class with a
premainmethod like this:
public class MyJavaAgent {
public static void premain(String agentArgs, Instrumentation inst) {
System.out.println("This is a Java Agent");
}
}
- Create a
resources/META-INF/MANIFEST.MFfile where you specify the location of the agent class.
Manifest-Version: 1.0
Main-Class: com.sergiomartinrubio.javaagentexample.Main
Premain-Class: com.sergiomartinrubio.javaagentexample.MyJavaAgent
The
MANIFEST.MFis a file that contains information about the files included in the.jarfile. i.e. You can set up the entry point of the application withMain-Classor a Java agent class withPremain-Class.
- Compile the application. You can use Maven with
maven-jar-pluginin yourpom.xmlfile.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifestFile>src/main/resources/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
</plugin>
</plugins>
</build>
- Run the generated Jar file with
-javaagentthat points to the.jarfile that contains the Java Agent (in this case is the same Jar file).
java -javaagent:/Users/sergiomartinrubio/workspace/java-agent-example/target/java-agent-example-1.0-SNAPSHOT.jar -jar target/java-agent-example-1.0-SNAPSHOT.jar
It is important that the
-javaagentparameter goes before the-jarparameter.
