- How Java/JVM agents work
- See also asm/byte buddy doc
- Agents can make arbitrary mutations to class files (even those already loaded)
- Agents can generate new class files
- Agents are deployed as jar files (so you must build them first)
- JVM allows multiple agents, executed in order specified on command line
- TODO: how to do multiple when packaged (approach 3)
- You specify Agent class in
src/main/resources/META-INF/MANIFEST.MF- attributes depend on approach, see below
- There are 3 ways to load agent
- Approach-1: Command line
- Approach-2: Attach to running JVM
- Approach-3: Bundled/Packaged with the application (into same Jar)
java -javaagent:/path/to/jar ...
java -javaagent:/path/to/jar=option1 ... <-- TODO: better exampleMANIFEST.MFmust containPremain-ClassattributePremain-Classattribute must point to a class withpublic static void premain(String agentArgs, Instrumentation inst) {method- Intellij will enforce
- Any code which is legal for
public static void main(...)is legal forpublic static void premain(...)
- TODO
MANIFEST.MFmust containLauncher-Agent-ClassattributeLauncher-Agent-Classattribute must point to a class withpublic static void agentmain(String agentArgs, Instrumentation inst) {method- Intellij will enforce
- JVM invokes
agentmain(...)method beforemain(...)method
- BootstrapClassLoader
- has no parent
- PlatformClassLoader
- Loads JDK
- System Class loader == AppClassLoader
- Loads your application classes
ClassNotFoundException: JVM cannot find definition for classNoClassDefFoundError: JVM aware of the class, it existed previously, but cannot find definition/code anymore
- Debugging
premaindoesn't work