Search code examples
javaagent

Self-injecting java agent


I am trying to create a self-injecting java agent. The agent and the code to dynamically load the agent would be contained in the same jar file.

I tried to do this by defining both Main-Class and Agent-Class in the manifest file. This is the file:

Manifest-Version: 1.0
Main-Class: myjar.injector
Agent-Class: myjar.agent

However, I get the following error when I run the jar: com.sun.tools.attach.AgentLoadException: Agent JAR not found or no Agent-Class attribute

When I inspected the compiled jar, there was only a Main-Class attribute in the jar's manifest file. I tried recompiling outside of my IDE, but there was still only the Main-Class attribute.

Is there any way to have both Main-Class and Agent-Class in a jar file?


Solution

  • Yes. Just put it there. You have some process that turns java source files into a jar file. I would hope it is maven or gradle or some other build system. It might be an IDE or a handrolled script. There's nothing magical about it: Your tool chain is messing this up.

    You can always check the manifest as follows:

    jar xvf myjar.jar META-INF/MANIFEST.MF
    cat META-INF/MANIFEST.MF