How to create a jvmti agent to view all loaded classes, objects and their fields

I want to write a java agent to work with some applications. I am interested in getting the details of objects (i.e. Their fields) created by applications. I would also like to catch any read and write access to any of these objects / their fields at runtime.

Can you refer me to agents in writing and tell me which classes and methods should be studied. I just know about the java.lang.instrument class. But I could not find anything there that could catch these events.

I am also open to any other Java toolkit tools that you think can help me.

+1
source share
1 answer

You can use AspectJ with weaving load times (javaagent). You can, for example, write aspects for tracking constructor calls (call points / execution points) and access to the monitor field (set / get points).

I use annotation based development. For example, to control the setting of all non-static non-final and non-transition fields in all classes in a given package, you can create an 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> 

Put acpectjrt.jar and aspectjweaver.jar in the class path and start the JVM with the -javaagent:lib/aspectjweaver.jar . Here are some examples and documentation http://www.eclipse.org/aspectj/doc/released/adk15notebook/ataspectj.html

+3
source

Source: https://habr.com/ru/post/1441546/


All Articles