我从未听说过premain,我觉得有些愚蠢,但是the answer of this post建议运行它以获得Instrumentation对象。

但是该函数如何被调用或如何使其被调用?

package playground;
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);
    }
}

最佳答案

premain是与java.lang.instrument包相关联的一种机制,用于加载“代理”,这些代理在Java程序中进行字节代码更改。

该机制在 java.lang.instrument documentation中进行了说明。

其要点是将“代理”部署在一个jar中,并且该jar在其 list 中有一个特殊的条目,该条目告诉工具包在哪里寻找premain方法。您引用的来源应该是一个简单的代理。

09-26 06:35