Skip to content

premain method

The premain method is the specific entry point for a Java Agent, designed to execute strictly before the application's standard main method.^[600-developer__java__black-technology__javaagent.md]

Definition and Signature

In the context of the Java Agent technology, which allows for the modification of bytecode at the Java runtime, the premain method serves as the hook that enables the agent to intervene in the application lifecycle.^[600-developer__java__black-technology__javaagent.md]

It must be defined as a public static void method that accepts a String for agent arguments and an Instrumentation object:^[600-developer__java__black-technology__javaagent.md]

public static void premain(String agentArgs, Instrumentation instrumentation)

Execution Timing

The defining characteristic of the premain method is its execution order: it is invoked by the JVM when the agent is loaded, which occurs strictly before the main method of the target application is executed.^[600-developer__java__black-technology__javaagent.md]

This sequence enables the agent to inspect or modify classes as they are loaded, facilitating techniques such as [[AOP|Aspect-Oriented Programming]] or reloading class file changes.^[600-developer__java__black-technology__javaagent.md]

Configuration and Deployment

To function, the class containing the premain method must be packaged into a JAR file with specific metadata in the META-INF/MANIFEST.MF file.^[600-developer__java__black-technology__javaagent.md]

The configuration requirements are:

  • Manifest Attributes:
    • Premain-Class: Specifies the fully qualified class name containing the premain method (e.g., tk.tommy.MyAgent).^[600-developer__java__black-technology__javaagent.md]
    • Can-Redefine-Classes: Set to true to indicate that the agent supports redefining classes at runtime.^[600-developer__java__black-technology__javaagent.md]
  • Invocation: The agent is loaded by passing the -javaagent:myagent.jar argument to the Java command. Arguments can also be passed to the agent using the format -javaagent:myagent.jar=thisIsAgentArgs.^[600-developer__java__black-technology__javaagent.md]

Sources