How to get a toolkit instance in Java

I am trying to write just an ObjectUtils class that contains many utility methods for all objects. I would like one of them to be called getObjectSize(Object) , where you pass it an instance of the object and return the size of the object 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 get an implemented instance of Instrumentation you need to do all kinds of fancy things with the help of JRE agents and the so-called premain method.

Is there an easy way to access local instances of JRE Instrumentation ? I searched for something through the Runtime API, but couldn't find anything.

+6
source share
1 answer

I found a class called InstrumentationFactory .

The first time someone requests an instance of Instrumentation , he creates an agent JAR file, then finds the PID of his own process and attaches it to the JVM inside this ... which calls his agentmain(..) , giving this an interesting example of Instrumentation .

I'm not sure how reliable this approach is. What I'll try is searching for OpenJDK code to find out where and how the instance of Instrumentation is created. Perhaps, in the absence of security requirements, it would be possible (through reflection) to get this mechanism to provide an instance of Instrumentation without having to attach or preload the agent?

0
source

Source: https://habr.com/ru/post/916300/


All Articles