S
S
synapse_people2018-08-31 14:33:29
Java
synapse_people, 2018-08-31 14:33:29

How to intercept all write operations on an object using bytecode modification?

For example, there is a method with a body:

... obj;
obj.field0 = 10;
obj.setSomeotherfield(12);

How can you call another method, for example, obj.onChanged, after each value rewriting or setter call?
That is, first find the variable of the required type (class), then find all writing calls/setting values, and then plug after each onChanged call. Ps obj.getSomeList().add(value)is also a beeping operation, in general, all method calls can be replaced, and in onChanged check whether hashCode has changed ....
Preferably with the help of javassist, if anyone knows a simpler option, write pliz
And also - what problems can there be with such an approach? Maybe there is a simpler option, how to intercept changes to an object and its sub-objects (properties and properties-properties-properties N in depth)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evhen, 2018-09-07
@synapse_people

Similar things are done with AspectJ
Here is an example of how to intercept the setters of all classes in the specified package demo-aspectj
class

package ua.evhen.aspectj.demo.domain;

public class BankAccount {

    private String pan;
    private String panSate;
    private String exDate;
    private String panName;
    private long clientId;

// getters and setter
}

aspect that will intercept calls to set* methods
package ua.evhen.aspectj.demo.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class BankAccountAspect {
    @Before("execution(void ua.evhen.aspectj.demo.domain.*.set*(..)) && args(val)")
    public void setMethod(Object val, JoinPoint jp) {
        System.out.printf("%s := '%s'%n ", jp.getSignature().toShortString(), val);
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question