Simple application of java agent

write the first agent

This section will discuss in detail how to write your first Java agent. We will write the first simple java agent as simply as possible, because this part is just a brief introduction to the usage of java agent. To write an agent, you need to write a class with a static premain() method, refer to the following:

[java] 
package net.javabeat.articles.javaagent.test; 
 
import java.lang.instrument.Instrumentation; 
 
public class TestJavaAgent { 
 
    public static void premain(String agentArgument, 
            Instrumentation instrumentation) { 
        System.out.println("Test Java Agent" ); 
    } 
 

Note: It is mandatory for a class to have the above methods to become an agent. The above agent does nothing but print something simple to the console.
[java]
Manifest-Version: 1.0 
Premain-Class: net.javabeat.articles.javaagent.test.TestJavaAgent 

Agents need to be packaged into jar files and start the application through the jvm startup parameter of "javaagent" so that the application can perceive the existence of the agent. Note that it is necessary for an agent's jar file to have the Premain-class attribute, because this attribute specifies the full path name of the agent class. Next, we will use this agent to do some things. We need to do some preparations. First, we need to create a simple java class as follows. Note that when the application is running, we call this agent, and calling an agent is specified by the parameters of the jvm of.
[java] 
package net.javabeat.articles.javaagent.test; 
 
public class TestMain { 
    public static void main(String[] args) { 
        System.out.println("Test Main Class"); 
    } 

Create a name test-agent.jar, and
open the console with "net.javabeat.articles.javaagent.test.TestJavaAgent" and the manifest file "MANIFET.MF", and start the application and agent with the following command java -javaagent:test -agent.jar net.javabeat.articles.javaagent.test.TestMain
 

In the console you will see the following output

[java] www.2cto.com
Test Java Agent 
Test Main Class 

Note: There are a few things to note in this part: First: the agent is run by passing parameters to the jvm. The specific process is to specify the javaagent parameter, followed by the javaagent is the path to specify the jar file. Second: The java agent is started before our application starts, as evidenced here by the output to the console.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325896590&siteId=291194637