javajarmanifestinstrumentation

Failed to find Premain-Class manifest attribute from a jar file


I created a jar from a single .class and I mentioned in the manifest the Premain-class, the jar was generated as expected but when I try to run a program that uses the class from that jar , I get an error

MANIFEST.MD

Premain-Class : Agent

Agent.java

import java.lang.instrument.Instrumentation;
public class Agent{
    private static Instrumentation inst;
    public static void premain(String paramString, Instrumentation paramInstrumentation) 
    { 
        inst = paramInstrumentation;
    }

    public static long size(Object paramObject)
    {
        return inst.getObjectSize(paramObject);
    }
}

Test.java

public class Test {

  public static void main (String[] args){
    System.out.println(Agent.size(Integer.valueOf(9)));
  }
}

When I get the Agent.class, in the same folder where MANIFEST.MD file exist I execute the following command

jar -cvfm agent.jar MANIFEST.MF *.class

and when I get the the jar I run the Test, after compiling it, as follow

java -javaagent:agent.jar Test

and I get the following error

Failed to find Premain-Class manifest attribute in agent.jar
Error occurred during initialization of VM
agent library failed to init: instrument

am I missing something ? thanks in advance


Solution

  • The MANIFEST specification doesn't seem to allow spaces after the key, but only before the value.

    header: alphanum *headerchar ":" SPACE *otherchar newline
              *continuation
    

    So this

    Premain-Class : Agent
    

    should become

    Premain-Class: Agent
    

    Also, put your Agent under a package, don't use the default one

    Premain-Class: your.package.Agent