如何创建jvmti代理以查看所有已加载的类,对象及其字段详细信息 [英] How to create a jvmti agent to see all the loaded classes, objects and their field details
问题描述
我想编写一个Java代理来检测某些应用程序.我对获取由应用程序实例化的对象(即它们的字段)的详细信息感兴趣.我还想在运行时捕获对任何这些对象/它们的字段的任何读写访问权限.
I want to write a java agent to instrument some applications. I am interested in getting the details of the objects, (i.e. their fields) instantiated by the applications. I would also like to catch any read and write access to any of those objects/their fields while running.
能否请您指导我编写代理,并让我知道我应该探索哪些类和方法.我只知道java.lang.instrument类.但是我在那里找不到任何可以捕捉到这些事件的东西.
Can you please guide me in writing the agents and let me know what classes and methods should I explore. I just know about java.lang.instrument class. But I could not find anything there that could catch these events.
我也接受您认为可以帮助我的其他Java工具技术.
I am also open to any other java instrumentation techniques that you think can help me.
推荐答案
您可以使用 AspectJ 使用加载时编织(javaagent).您可以例如编写方面以监视构造函数调用(调用/执行切入点)和监视字段访问(设置/获取切入点).
You can use the AspectJ with load-time weaving (javaagent). You can e.g. write aspects to monitor constructor calls (call/execution pointcuts) and monitor field access (set/get pointcuts).
我正在使用基于注释的开发.例如,要监视给定程序包中所有类中所有非静态非最终和非瞬态字段的设置,您可以创建方面:
I'm using annotation-based development. For example to monitor setting all nonstatic nonfinal and nontransient fields in all classes in given package you can create aspect:
@Aspect
public class MonitorAspect {
@Around(" set(!static !final !transient * (*) . *) && args(newVal) && target(t) && within(your.target.package.*) ")
public void aroundSetField(ProceedingJoinPoint jp, Object t, Object newVal) throws Throwable{
Signature signature = jp.getSignature();
String fieldName = signature.getName();
Field field = t.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
Object oldVal = field.get(t);
System.out.println("Before set field. "
+ "oldVal=" + oldVal + " newVal=" + newVal + " target.class=" + t.getClass());
jp.proceed();
}
}
在META-INF中放置aop.xml:
in META-INF place aop.xml:
<?xml version="1.0" encoding="UTF-8"?>
<aspectj>
<aspects>
<aspect name="your.package.MonitorAspect" />
</aspects>
</aspectj>
将acpectjrt.jar和Aspectjweaver.jar放在类路径上,并使用-javaagent:lib/aspectjweaver.jar
参数运行JVM.
以下是一些示例和文档 http://www.eclipse.org/aspectj /doc/released/adk15notebook/ataspectj.html
Place acpectjrt.jar and aspectjweaver.jar on classpath and run your JVM with -javaagent:lib/aspectjweaver.jar
parameter.
Here are some examples and documentation http://www.eclipse.org/aspectj/doc/released/adk15notebook/ataspectj.html
这篇关于如何创建jvmti代理以查看所有已加载的类,对象及其字段详细信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!