尝试使用java代理获取对象的大小时"无法加载Premain-Class清单属性"

jav*_*eek 14 java instrumentation agent

当我尝试运行java程序(java -javaagent:size.jar ObjectSizeTest)时,我收到以下错误:

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
Run Code Online (Sandbox Code Playgroud)

这是ObjectSizeTest的代码:

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

MANIFEST.MF(适用于size.jar):

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

Premain-Class: ObjectSizeFetcher
Run Code Online (Sandbox Code Playgroud)

这是ObjectSizeFetcher的代码:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 8

确保您已提供包含pre-main方法的类的完整java路径.例如像org.eclipse.anotherpckg.ObjectSizeFetcher.其次,名称和运输结束前必须有一个空格.例如

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

最后一行是由于回车.

  • 它在此代码段中不可见,但文件末尾的新行确实是必要的. (2认同)

Max*_*nov 6

您应该在 MANIFEST.MF 中添加:

Premain-Class: org.your.package.ObjectSizeFetcher + 新线

插入

Premain-Class: ObjectSizeFetcher