public static synchronized Instrumentation getInstrumentation() throws ClassNotFoundException, InvocationTargetException, IOException, NoSuchMethodException, IllegalAccessException {
if (_inst != null || !_dynamicallyInstall)
return _inst;
// dynamic loading of the agent is only available in JDK 1.6+
if (JavaVersions.VERSION < 6)
return null;
String agentPath = getAgentJar();
// first obtain the PID of the currently-running process
// ### this relies on the undocumented convention of the RuntimeMXBean's
// ### name starting with the PID, but there appears to be no other
// ### way to obtain the current process' id, which we need for
// ### the attach process
RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
String pid = runtime.getName();
if (pid.indexOf("@") != -1)
pid = pid.substring(0, pid.indexOf("@"));
// JDK1.6: now attach to the current VM so we can deploy a new agent
// ### this is a Sun JVM specific feature; other JVMs may offer
// ### this feature, but in an implementation-dependent way
Class vmClass = Class.forName("com.sun.tools.attach.VirtualMachine");
Object vm = vmClass.getMethod("attach", new Class[] { String.class }).
invoke(null, new String[] { pid });
// now deploy the actual agent, which will wind up calling agentmain()
vm.getClass().getMethod("loadAgent", new Class[] { String.class }).
invoke(vm, new Object[] { agentPath });
if (_inst != null)
return _inst;
return null;
}
|