23

When i try to run a java program (java -javaagent:size.jar ObjectSizeTest) i get the following error:

Failed to load Premain-Class manifest attribute from D:\workspace\ObjectSizeTest\size.jar
Error occurred during initialization of VM
agent library failed to init: instrument

Here is ObjectSizeTest's code:

public class ObjectSizeTest {
    public static void main(String[] args) {
        String s = new String("sai");
        System.out.println(ObjectSizeFetcher.getObjectSize(s));
    }
}

MANIFEST.MF (for size.jar):

Manifest-Version: 1.0
Created-By: 1.5.0_18 (Sun Microsystems Inc.)

Premain-Class: ObjectSizeFetcher

and here is ObjectSizeFetcher's code:

import java.lang.instrument.Instrumentation;

public class ObjectSizeFetcher {
    private static Instrumentation instrumentation;

    public static void premain(String args, Instrumentation inst) {
        instrumentation = inst;
    }

    public static long getObjectSize(Object o) {
        return instrumentation.getObjectSize(o);
    }
}
haggai_e
  • 4,689
  • 1
  • 24
  • 37
java_geek
  • 17,585
  • 30
  • 91
  • 113

4 Answers4

10

Make sure you have give full java path of the class containing the pre-main method. for example like this org.eclipse.anotherpckg.ObjectSizeFetcher. Secondly there must be a space before the name and carriage return at the end. for example

Manifest-Version: 1.0
Created-By: 1.5.0_18 (Sun Microsystems Inc.)
Premain-Class: org.eclipse.package.ObjectSizeFetcher

The last line is due to carriage return.

user758867
  • 121
  • 1
  • 5
6

You should add in MANIFEST.MF:

Premain-Class: org.your.package.ObjectSizeFetcher + new line

insted

Premain-Class: ObjectSizeFetcher

Max Gabderakhmanov
  • 912
  • 1
  • 18
  • 36
2

It is an issue with the jar command itself. jar command must be used with cfm attributes, to include customized MANIFEST.MF, otherwise jar will create one file and insert its own contents which do not include the PreMain-Class attribute as we mention in customized manifest.mf file.

maruthy
  • 21
  • 1
  • I'm logging in just to upvote this answer as `cfm` (especially the `m`) is exactly what solved my problem. The claim of having to use "new line" in the manifest file in other answers is pure wrong. – GJ. Mar 08 '23 at 03:08
0

just run java size.jar ObjectSizeTest the problem is caused by java agent it has a tranformer class.

jackson
  • 16
  • 3