Skip to content

Instantly share code, notes, and snippets.

@xnike
Created September 19, 2016 16:45
Show Gist options
  • Save xnike/a268fc209df52bf1bf09a268e97cef53 to your computer and use it in GitHub Desktop.
Save xnike/a268fc209df52bf1bf09a268e97cef53 to your computer and use it in GitHub Desktop.
Simple snippet to show how to attach javaagent to running JVM process
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
public class AgentRunner {
/*
* This class shows how to attach hotswap-agent.jar to a running JVM process and overload classes using "extraClasspath=" property via Hotswapper plugin.
*
* Lets assume that:
* args[0] contains pid of running JVM process or a runner class name we want to attach agent to
* args[1] contains absolute path to agent.jar
* args[2] contains parameters needed to pass to agent
*/
public static void main(String[] args) {
if (2 > args.length) {
System.out.println("Usage: java -cp .:$JAVA_HOME/lib/tools.jar AgentRunner JVM_PID_OR_NAME PATH_TO_JAR [PARAMS]");
} else try {
String pid = args[0];
for (VirtualMachineDescriptor vmd : VirtualMachine.list()) {
if (vmd.displayName().contains(args[1])) {
pid = vmd.id();
break;
}
}
final VirtualMachine vm = VirtualMachine.attach(pid);
vm.loadAgent(args[1], 3 > args.length || null == args[2] ? "" : args[2]);
vm.detach();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment