Load a java agent during runtime on OpenJDK?

1.3k views Asked by At

I've found many answers pointing me to VirtualMachine#loadAgent, which would honestly be great, except I don't have a VirtualMachine class, anywhere. I've been quite confused about it as well, however I do not seem to have any of the Attach API. I am using OpenJDK 8:

$ java -version
openjdk version "1.8.0_222"
OpenJDK Runtime Environment (build 1.8.0_222-b05)
OpenJDK 64-Bit Server VM (build 25.222-b05, mixed mode)

What other methods are there to load a java agent? The environment I am working in would have very little success at passing -javaagent: arguments, as it's meant to be injected into the classpath at runtime, and obviously any average user isn't going to want to/have the knowledge to manually change the JVM args just for my specific program.

On another note, just to make sure that this class is meant to be a part of OpenJDK, as isn't something designed only for the java hotspot VM, I downloaded OpenJDK code from http://hg.openjdk.java.net/, and found the VirtualMachine.java file, which means that it definitely is meant to exist

1

There are 1 answers

0
Stephen C On BEST ANSWER

I've found many answers pointing me to VirtualMachine::loadAgent, which would honestly be great, except I don't have a VirtualMachine class, anywhere.

Lets start this the javadocs for VirtualMachine and VirtualMachineDescriptor

Clearly, the VirtualMachine class is defined by the Java class libraries, so the class exists. So the question is why you can't find the class itself at compile time and/or at runtime.

For older JVMs prior to Java 6, the VirtualMachine class was semi-internal and you needed to access it from the tools.jar file:

When the VirtualMachine class became an official API in Java 6, its name changed to com.sun.tools.attach.VirtualMachine. However, it was still in the tools.jar file rather than the main rt.jar file. This continued until (and including) Java 8.

In Java 9, the modules system was introduced and things changed. Neither rt.jar or tools.jar exist anymore. To access these classes now (Java 9 onwards) you need to include requires jdk.attach in your module.info file.