Is it possible to insert a javaagent after virtual machine start from within the same VM?
Lets say for example we have an agent in a jar myagent.jar with the appropriate meta data set-up and an agentmain method already implemented. Now the users program calls an API call which should result in the insertion of the agent so that it can redefine the classes.
Can it be done and how?
https://web.archive.org/web/20141014195801/http://dhruba.name/2010/02/07/creation-dynamic-loading-and-instrumentation-with-javaagents/ has a great example of how to write an agent as well as how to start one on the fly.
Yes, you just have to pass the JVM process ID to the VirtualMachine.attach(String pid)
method, and load the agent jar. The VirtualMachine
class is available in the JDK_HOME/lib/tools.jar file. Here's an example of how I activate an agent at runtime:
public static void attachGivenAgentToThisVM(String pathToAgentJar) {
try {
String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();
String pid = nameOfRunningVM.substring(0, nameOfRunningVM.indexOf('@'));
VirtualMachine vm = VirtualMachine.attach(pid);
vm.loadAgent(pathToAgentJar, "");
vm.detach();
} catch (Exception e) {
e.printStackTrace();
}
}
You should be able to do it in Java 6, see the package documentation chapter "Starting Agents After VM Startup"
edit: Maybe it was possible in Java 5 already and just the javadocs didn't mention it that explicitly
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With