Skip to content
Advertisement

Get jar manifest attributes from Java agent

I am running my own java agent on a jar containing some sample code. Input to the command line:

java -javaagent:path/to/agent.jar=path/to/main-class -jar path/to/sample-code.jar

I’m currently providing the sample-code.jar‘s main class (as stated in its manifest) as an arg to the agent, although, I’m trying to find a way to access the sample-code.jar‘s manifest’s Main-Class attribute from within the agent’s premain.

I tried some of the answers suggested here: Reading my own Jar’s Manifest, although, no luck – I think the approaches I tried require everything to have already been fully loaded.

Any suggestions are much appreciated.

Advertisement

Answer

Turns out a combination of the linked question’s answers worked for me (note loader is already provided as an arg in a ClassFileTransformer‘s transform method).

URL url = loader.getResource("META-INF/MANIFEST.MF");
if (url == null) {
    throw new RuntimeException("Can't locate manifest.");
}
try {
    Manifest manifest = new Manifest(url.openStream());
    Attributes attr = manifest.getMainAttributes();
    String mainClass = attr.getValue("Main-Class").replace(".", "/");
} catch (IOException e) {
    e.printStackTrace();
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement