如何在 Eclipse RCP 应用程序中使用 java.lang.instrument?
为了使用 JDK 5 中引入的检测功能,您可以使用传递给 JVM 的 -javaagent
标志。这会将 Instrumentation 类的实例注入到静态 premain
方法中。例如,在这样的类中:
public class MyClass {
public static Instrumentation inst;
public static void premain(String options, Instrumentation inst) {
MyClass.inst = inst;
}
}
使用适当的清单文件,您可以按如下方式运行:
java -javaagent:myfiles.jar SomeClass
这将调用 premain 方法,然后调用 SomeClass
中的 main
方法。 Java.SizeOf 项目 使用此方法来猜测 Java 对象的大致大小。
好的,现在在 Eclipse RCP 中每个包都有自己的类加载器。这意味着我们存储在 MyClass 中的静态 Instrumentation 对于 Eclipse 应用程序是不可见的。 javaagent 使用一个类加载器,Eclipse 包使用另一个类加载器进行加载。当我们从插件中访问MyClass.inst
时,它是null
,因为那个类与javaagent加载的类不同,并且调用了 premain
。
有关可能解决方案的其他线索是此线程 在 rcp 邮件列表上。但没有什么定论。
有什么办法可以解决这个问题吗? eclipsezone 文章中暗示的 Eclipse-BuddyPolicy 听起来不错。我尝试过:
Eclipse-BuddyPolicy: app
在我的插件中没有运气。我需要类似 Eclipse-BuddyPolicy: javaagent
的东西。有什么想法吗?
In order to use the instrumentation features introduced in JDK 5, you can use the -javaagent
flag passed to the JVM. This will inject an instance of an Instrumentation class into the static premain
method. For example in a class like this:
public class MyClass {
public static Instrumentation inst;
public static void premain(String options, Instrumentation inst) {
MyClass.inst = inst;
}
}
With an appropriate manifest file, you can run this as follows:
java -javaagent:myfiles.jar SomeClass
This calls the premain method then main
from SomeClass
. This approach is used in the Java.SizeOf Project to guess at the approximate size of a Java object.
OK, now in Eclipse RCP each bundle has its own classloader. This means that the static Instrumentation that we stored in our MyClass is not visible to an Eclipse application. The javaagent uses one class-loader, the Eclipse bundles get loaded with another. When we access MyClass.inst
from within a plugin it is null
, as that class is not the same class as the one the javaagent loaded and called premain
on.
Other clues as to a possible solution are this thread on the rcp mailing list. But nothing conclusive.
Is there any way to work around this? The Eclipse-BuddyPolicy
hinted at in the eclipsezone article sounds good. I tried:
Eclipse-BuddyPolicy: app
in my plugins without luck. I need something like Eclipse-BuddyPolicy: javaagent
. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为最简单的解决方案是使用全局属性对象。让 pre-main 将检测对象存储为全局属性,然后从任何地方访问它(属性对象在所有类加载器中都是相同的):
[编辑:更新]
I think the simplest solution is to use the global properties object. Have pre-main store the instrumentation object as a global properties and then access it from everywhere (the properties object is the same in all class loaders):
[Edit: updated]