Preston Garno
Preston Garno

Reputation: 1215

How should I specify my Premain-class in manifest.mf when starting JVM with -javaagent

I'm currently trying to experiment with Java Instrumentation, and I'm having trouble even starting the JVM with the -javaagent arg and getting a ClassNotFoundException.

I have a simple test project called TestInstrumentation. It has a src folder with a package called testinstrumentation. Inside is: TestInstrumentation.java and TestAgent.jar.

Here is the contents of my TestAgent.jar's manifest.mf:

Manifest-Version: 1.0
Premain-Class: TestAgent
Created-By: 1.8.0_45 (Oracle Corporation)

TestAgent.java:

package testinstrumentation;

import java.lang.instrument.Instrumentation;

public class TestAgent {
    public static void premain(String agentArgument, Instrumentation instrument) {
        System.out.println("Java Agent Loaded!");
    }
}

TestInstrumentation.java:

package testinstrumentation;

public class TestInstrumentation {
    public static void main(String[] args) {
        System.out.println("Main Class");
    }

}

Here is the stacktrace when I try to run it:

java.lang.ClassNotFoundException: TestAgent
FATAL ERROR in native method: processing of -javaagent failed
    at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:304)
    at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:401)
Exception in thread "main" Java Result: 1

I'm pretty sure the error is in my specification of the Premain-class in the manifest.mf of my jar. Any suggestions as to how I could get this corrected would be appreciated!

Upvotes: 3

Views: 7596

Answers (1)

Mark Bramnik
Mark Bramnik

Reputation: 42481

It sounds more like a packaging issue. In general you do it right: You have to specify the following in your manifest.

Premain-Class: testinstrumentation.TestAgent

Of course, the testinstrumentation.TestAgent class file should reside in the same jar. From your stacktrace I see that it looks in src.testinstrumentation however your code is supposed to be put into testinstrumentation package

I recommend reading the Not so secret Java agents series of tutorials (4 parts). This provides a pretty good overview of capabilities of Java agents.

Upvotes: 3

Related Questions