我有这门课:
public class UnusedJarDetector {
public static void onDefineClass(Class<?> clazz, ClassLoader classLoader) {
...
}
public static void onGetResource(URL url, ClassLoader classLoader) {
...
}
...
为了调用这些方法,我必须从 jdk1_6_0_31 中修补 java.lang.ClassLoader
并将其添加到 Bootstrap 中。但是当然,修补后的类不适用于其他 JRE 版本。
更新:是否可以在配置文件模式下启动 java 并处理 defineClass()
和 getResource()
的返回值?
--- ClassLoader.java.orig 2014-08-07 11:57:47.851455900 +0400
+++ ClassLoader.java 2014-08-07 12:00:55.045096600 +0400
@@ -612,7 +615,9 @@
ProtectionDomain protectionDomain)
throws ClassFormatError
{
- return defineClassCond(name, b, off, len, protectionDomain, true);
+ Class<?> clazz = defineClassCond(name, b, off, len, protectionDomain, true);
+ UnusedJarDetector.onDefineClass(clazz, this);
+ return clazz;
}
// Private method w/ an extra argument for skipping class verification
@@ -1001,6 +1006,7 @@
if (url == null) {
url = findResource(name);
}
+ UnusedJarDetector.onGetResource(url, this);
return url;
}
最佳答案
可以使用 java.lang.instrument 来做到这一点. Kyrill Alyoshin 的一个名为“loosejar”的项目使用 java.lang.instrument 来执行我认为您在这里尝试执行的操作,通过 JMX 公开其结果,以便您可以在应用程序使用 jconsole 或 jvisualvm 运行时看到它们。参见 this blog entry .
关于java - 每次加载类或找到资源时如何执行操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25179863/