java 什么是 premain() 以及如何调用它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27851588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:31:14  来源:igfitidea点击:

What is premain() and how does it get called?

javamethods

提问by displayname

I have never heard of a premainand I feel a little stupid to ask but the answer of this postsuggests to run it in order to get the Instrumentationobject.

我从未听说过 apremain并且我觉得问起来有点愚蠢,但这篇文章的答案建议运行它以获取Instrumentation对象。

But how does that function get called or how do I make it getting called?

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

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

回答by RealSkeptic

The premainis a mechanism associated with the java.lang.instrumentpackage, used for loading "Agents" which make byte-code changes in Java programs.

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

The mechanism is explained in the java.lang.instrumentdocumentation.

该机制在java.lang.instrument文档中进行了解释。

The gist of it is that the "agent" is deployed in a jar, and that jar has a special entry in its manifest, that tells the instrumentation package where to look for the premain method. The source you quoted is supposed to be a simple agent.

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