javaagent¶
javaagent is a specialized Java technology that allows for the modification of bytecode at the Java runtime^[600-developer__java__black-technology__javaagent.md]. It enables specific logic to be executed before the main method of a Java application runs^[600-developer__java__black-technology__javaagent.md].
Mechanism¶
The core functionality of a Java Agent is defined by a specific entry point known as the premain method^[600-developer__java__black-technology__javaagent.md]. This method is invoked prior to the execution of the application's main method, serving as a hook for initializing instrumentation or logic modification^[600-developer__java__black-technology__javaagent.md].
This mechanism is commonly utilized to implement [[aop|Aspect-Oriented Programming (AOP)]] without modifying the source code directly^[600-developer__java__black-technology__javaagent.md].
Implementation Requirements¶
To create and deploy a Java Agent, several specific configurations and packaging requirements must be met^[600-developer__java__black-technology__javaagent.md]:
- Packaging: The agent must be packaged as a JAR file^[600-developer__java__black-technology__javaagent.md].
- Manifest Configuration: The JAR's
META-INF/MANIFEST.MFfile must define thePremain-Classattribute, which specifies the class containing thepremainmethod^[600-developer__java__black-technology__javaagent.md]. - Capabilities: The manifest file typically includes
Can-Redefine-Classes: trueto indicate that the agent can redefine classes at runtime^[600-developer__java__black-technology__javaagent.md].
Usage¶
A Java Agent is loaded via the JVM command line using the -javaagent option^[600-developer__java__black-technology__javaagent.md]. This allows the user to pass the path to the agent JAR and optional arguments.
The standard invocation syntax is:
-javaagent:myagent.jar=thisIsAgentArgs
For example, when running an application, the command might look like this:
java -javaagent:myagent.jar=thisIsAgentArgs -jar thisIsMain.jar^[600-developer__java__black-technology__javaagent.md]
Related Concepts¶
- [[aop|AOP]]
- [[Bytecode Manipulation]]