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
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论