user6397000
user6397000

Reputation: 65

How to intercept field accesses (without getter/setter) using Bytebuddy

I am trying to use bytebuddy to intercept getfield and putfield accesses. I have read the rather comprehensive documentation on the site, but from what I can understand, it covers adding getters and setters to fields, rather than intercepting field accesses.

Here is basically what I am trying to do:

...
obj.prop = value;
x = obj.prop;
...

That in both these cases, I am trying to have some method called (or some bytecode inserted) before/after the field access. I was thinking of using Advice to do it, but I am unable to find a way to have it for something other than methods.

Edit:

I am using a Java Agent to do it. I had an idea of adding a dup to duplicate the object reference followed by the call to a static method I defined to intercept the access (I only care about the object being referred to, not the field).

Upvotes: 4

Views: 912

Answers (1)

Rafael Winterhalter
Rafael Winterhalter

Reputation: 44007

There is a new component that is still under development but that is already exposed with a basic API. It is called MemberSubstitution and allows you to replace a method call or field access with another execution.

This component does however rely on replacing the code that executes an instruction. Field access is non-virtual, therefore it is not possible to create any proxy class that would intercept a virtual access. Instead, you have to redefine any existing class that reads or writes the field, for example by using a Java agent.

As for your more specific question: At the moment, there is only a 1-to-1 substitution possible. I have not yet had the time to include a mechanism for adjusting the stack and local variable sizes. Also, you would also have to dup objects lower down on the stack if the field is non-static. The problem is not trivial so to say but I hope to offer such functionality some day.

At the moment you can however replace the field access with a static method call. Possibly, you can execute the original field operation from this method.

Upvotes: 5

Related Questions