Search code examples
javabyte-buddy

Field writer interceptor


I'am studying Byte Buddy and I am trying to replace CGLib by it. I want to know if there is a way to implement to intercept writing to any field. I do not know the field type and I do not want to change the assigned value. I only want to log field written! on any access.

Example: if I have this class:

public class Ex {
    public int i;
    public String s;
    public boolean b;
}

later when I do this:

Ex e = new Ex();
e.i=1;
System.out.println("Value of i:" + i);
e.s="hello";
System.out.println("Value of s:" + hello);

it should output:

field written!
Value of i: 1
field writed!
Value of s: hello

In the help page under Custom Instrumentation, there is an example but it's not clear.


Solution

  • No, that is not possible. Is this something you were doing using cglib? Because this is neither possible using Byte Buddy nor using cglib.

    The problem is that a field is not dispatched dynamically. Rather than redefining the class containing the field, you would need to redefine any class accessing the field what is close to impossible.