How to obtain instance of Instrumentation in Java

旧时模样 提交于 2020-05-13 02:27:20

问题


I am trying to write a simply ObjectUtils class that contains a variety of utility methods for all Objects. I would like to have one of them called getObjectSize(Object) where you pass it an instantiated Object and it returns the Object's size in memory:

public class ObjectUtils {
    private static volatile Instrumentation instrumentation;

    public static final long getObjectSize(final Object p_oToGauge)
    {
        return instrumentation.getObjectSize(p_oToGauge);
    }
}

However, it seems that in order to obtain an implemented Instrumentation instance, you need to do all sorts of fancy things with JRE agents and a so-called premain method.

Is there an easy way to get access to the local JRE's Instrumentation instances? I looked for something through the Runtime API but could find nothing.


回答1:


I found a class called InstrumentationFactory.

The first time someone asks for an instance of Instrumentation, it creates an agent JAR file, then finds the PID of its own process and attaches it to the JVM inside that... Which calls its agentmain(..), giving it the Instrumentation instance of interest.

I'm not sure how reliable that approach is. What I would try next is search the code of OpenJDK to see where and how an Instrumentation instance is created. Perhaps, in the absence of security requirements, it would be possible (via reflection) to get that mechanism to furnish an Instrumentation instance without having to attach or preload an agent?



来源:https://stackoverflow.com/questions/10692357/how-to-obtain-instance-of-instrumentation-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!