如何在Eclipse RCP应用程序中使用java.lang.instrument?

ric*_*chq 5 java instrumentation eclipse-rcp

为了使用JDK 5中引入的检测功能,您可以使用-javaagent传递给JVM 的标志.这将把一个Instrumentation类的实例注入到静态premain方法中.例如,在这样的类中:

public class MyClass {
    public static Instrumentation inst;
    public static void premain(String options, Instrumentation inst) {
        MyClass.inst = inst;
    }
}
Run Code Online (Sandbox Code Playgroud)

使用适当的清单文件,您可以按如下方式运行:

 java -javaagent:myfiles.jar SomeClass
Run Code Online (Sandbox Code Playgroud)

这将调用的premain方法,然后mainSomeClass.在Java.SizeOf Project中使用此方法来猜测Java对象的大致大小.

好的,现在在Eclipse RCP中,每个bundle都有自己的类加载器.这意味着我们存储在MyClass中的静态Instrumentation对Eclipse应用程序不可见.javaagent使用一个类加载器,Eclipse bundle加载另一个.当我们访问MyClass.inst从插件中它null,因为类是不一样的类作为一个javaagent加载,并呼吁premain对.

有关可能解决方案的其他线索是rcp邮件列表中的此线程.但没有定论.

有什么方法可以解决这个问题吗?Eclipse-BuddyPolicyeclipsezone文章中的暗示听起来不错.我试过了:

Eclipse-BuddyPolicy: app
Run Code Online (Sandbox Code Playgroud)

在我的插件没有运气.我需要类似的东西Eclipse-BuddyPolicy: javaagent.有任何想法吗?

Ita*_*man 5

我认为最简单的解决方案是使用全局属性对象。让 pre-main 将检测对象存储为全局属性,然后从任何地方访问它(属性对象在所有类加载器中都相同):

[编辑:更新]

public class MyClass {
    private static final String KEY = "my.instrumentation";
    public static void premain(String options, Instrumentation inst) {
        Properties props = System.getProperties();
        if(props.get(KEY) == null)
           props.put(KEY, inst);
    }

    public static Instrumentation getInstrumentation() { 
       return System.getProperties().get(KEY);
    }
}
Run Code Online (Sandbox Code Playgroud)