问题描述
我正在尝试编写一个简单的ObjectUtils
类,其中包含所有对象的多种实用程序方法.我想使用其中一个名为getObjectSize(Object)
的对象,在其中将实例化的对象传递给它,然后它返回该对象在内存中的大小:
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);
}
}
但是,为了获得已实现的Instrumentation
实例,您似乎需要使用JRE代理和所谓的premain
方法来完成各种花哨的事情.
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.
是否有一种简单的方法来访问本地JRE的Instrumentation
实例?我通过Runtime
API寻找了东西,但什么也没找到.
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.
推荐答案
我发现了一个名为 InstrumentationFactory
.
I found a class called InstrumentationFactory
.
第一次有人请求Instrumentation
的实例时,它会创建一个代理JAR文件,然后查找其自身进程的PID,并将其附加到JVM内的JVM中.它是感兴趣的Instrumentation
实例.
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.
我不确定该方法的可靠性.接下来,我将尝试搜索OpenJDK的代码,以查看在何处以及如何创建Instrumentation
实例.也许,在没有安全要求的情况下,有可能(通过反射)使该机制提供Instrumentation
实例,而不必附加或预加载代理?
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?
这篇关于如何获取Java中的Instrumentation实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!