5

To tell the JVM to invoke a Java Instrumentation agent before the main class of a Jar file, you usually have to invoke it with a command option:

java -javaagent:agent.jar program.jar

Having to type this out every time is pretty inconvenient, so is there a way to specify the agent in the program.jar manifest?

# program.jar/META-INF/MANIFEST.MF
...
Java-Agent: agent.jar
Clashsoft
  • 11,553
  • 5
  • 40
  • 79
  • 1
    At the end of [this answer](http://stackoverflow.com/a/19912148/2711488) is a sample code using the Attach API to attach to itself, in other words, starting itself as Java agent. It’s main purpose is to get hand on the `Instrumentation` implementation instance. If that’s your goal, you’re already done. If you know for sure that your code will be contained in a jar file already having the necessary `Agent-Class: ` manifest entry, you could simplify that solution by skipping the creation of the dummy jar file. – Holger Dec 15 '16 at 14:25

2 Answers2

4

Java 9 adds the Launcher-Agent-Class attribute which can be used on executable JAR files to start an agent before the main class is loaded.

Alan Bateman
  • 5,283
  • 1
  • 20
  • 25
1

Unfortunately, there is no such option. As an alternative, you can use the attach API to attach a Java agent dynamically. This does however have some limitations, e.g. it typically only works on a JVM that is distributed with a JDK.

For a convenient API for attaching agents, have a look at Byte Buddy Agent.

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192