57

I'd like to learn something about javaagents, but researching is not easy. Most of result refers to JADE. I know java agent can mean two things:

  1. An agent programmed in Java being an incarnation of the agent concept of distributed systems.
  2. A low-level software component to augment the working of a JVM, such as profilers, code-coverage tools, etc

I've found similar question here, but unfortunately it also refers to version 1.

Do you know any articles, tutorials for beginners, sample project about javaagent in version 2? I've found one here, but I'm looking for more.

Community
  • 1
  • 1
alicjasalamon
  • 4,171
  • 15
  • 41
  • 65
  • 1
    http://stackoverflow.com/questions/1277219/starting-a-java-agent-after-program-start also has some useful links – Vadzim Oct 23 '12 at 14:08

2 Answers2

88

The second case talks about Java Instrumentation API - this link points to a Javadoc which is rather descriptive.

And here, is the full instruction and an example of how to create java instrumentation agent.

The main concept is to:

  1. Implement a static premain (as an analogy to main) method, like this:

    import java.lang.instrument.Instrumentation;
    
    class Example {
        public static void premain(String args, Instrumentation inst) {
            ...
        }
    }
    
  2. Create a manifest file (say, manifest.txt) marking this class for pre-main execution. Its contents are:

    Premain-Class: Example
    
  3. Compile the class and package this class into a JAR archive:

    javac Example.java
    jar cmf manifest.txt yourAwesomeAgent.jar *.class
    
  4. Execute your JVM with -javaagent parameter, like this:

    java -javaagent:yourAwesomeAgent.jar -jar yourApp.jar
    
ZygD
  • 22,092
  • 39
  • 79
  • 102
npe
  • 15,395
  • 1
  • 56
  • 55
  • 19
    It is important that the `-javaagent` parameter goes before the `-jar` parameter. – berezovskyi Jul 17 '14 at 09:56
  • 1
    I had to add an additional entry to my manifest to get it to work with using Javassist. You can see in my answer to this question: https://stackoverflow.com/questions/10423319/how-do-you-analyze-fatal-javaagent-errors – 11101101b Oct 30 '14 at 20:44
  • 2
    I recently followed these steps to build an agent. I kept running into problems creating the jar, until I found out that the command should have listed the target .jar file first and the manifest file after. – end-user Jan 13 '16 at 17:47
  • You may also need to provide an empty `main` method in the `Example` class, or an error may be thrown complaining about the lack of the main method. – Searene Jan 04 '19 at 09:24
  • remember to finish the manifest.txt whit a blank line – villanueva.ricardo Feb 21 '20 at 15:08
6

Few useful resources for the javaagent as described in point #2.

devmake
  • 5,222
  • 2
  • 28
  • 26