开发者

How to create a jvmti agent to see all the loaded classes, objects and their field details

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.

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 t开发者_JS百科hese events.

I am also open to any other java instrumentation techniques that you think can help me.


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();
    }
}

in META-INF place aop.xml:

<?xml version="1.0" encoding="UTF-8"?>
<aspectj>
    <aspects>
        <aspect name="your.package.MonitorAspect" />
    </aspects>
</aspectj>

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜