see: Java - Instrumentation API & Java Agents
to use a Java Agent, you must load in 1 of the following ways:
- static load - makes use of the premain to load the agent using
-javaagentoption - dynamic load - makes use of the agentmain to load the agent into the JVM using the Java Attach API
Static Load
Static load modifies the byte-code at startup time before any code is executed. Keep in mind that the static load uses the premain method, which will run before any application code runs, to get it running we can execute:
java -javaagent:java-agent-here.jar -jar application.jar
IMPORTANT always put the –javaagent parameter before the –jar parameter
Dynamic Load
create an AgentLoader class that dynamically loads our agent to the application
VirtualMachine jvm = VirtualMachine.attach(jvmPid);
jvm.loadAgent(agentFile.getAbsolutePath());
jvm.detach();
In the application main:
public class Launcher {
public static void main(String[] args) throws Exception {
if(args[0].equals("StartMyAtmApplication")) {
new MyAtmApplication().run(args);
} else if(args[0].equals("LoadAgent")) {
new AgentLoader().run(args);
}
}
}
Starting the Application:
java -jar application.jar StartMyAtmApplication
Attaching Java Agent (after the first operation, we attach the java agent to our JVM):
java -jar application.jar LoadAgent