0

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.

  • 1
    I am happy you found an anyswer by yourself, but this is a typical case of the [XY problem](https://meta.stackexchange.com/a/66378/309898): You did not explain what you were trying to achieve, only how you thought it should be done. So now that you know the executable JAR's main class, what are you going to do with that information? – kriegaex Aug 27 '22 at 13:09

1 Answers1

0

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();
}
  • 1
    But there is no guaranty that the JVM your agent is running in has been started with the `-jar` option. It could have been started with `-cp path/to/sample-code.jar entirely.different.MainClass`. It could also use modules. – Holger Aug 30 '22 at 09:01