Is there any way(framework/library) to watch changes on class variables?

My project has requirement to know whether use change data or not but i’m not allowed to modify data model itself. For example i have class like this:

public class Person {
    String firstName;
    String lastName;
    Address address;
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public Address getAddress() {
        return lastName;
    }
    public void setAddress(Address address) {
        this.address= address;
    }

}

And it should always be POJO like this, i can’t invoke any other methods in getter/setter, so that there is some solutions but it’s not fit with my requirement:

  • How to detect if a variable has changed?
  • How to watch a variable for changes
  • How to create change listener for variable?

I also can not apply Observer Pattern here.

My current solution is: after init person instance, i parse it to json and create hashcode (MD5), whenever i want to check changes, i do that logic again and compare new hashcode with old one. if it’s not the same that mean my data has changed. Somehow it work fine but i’m still worried about it, not sure it’s good way or not.

Futhermore if there is any framework/library can provide this feature, it’s great.

Does anyone know some?

Thanks

It depends on some factor:

Is POJO serializable / implements hashCode / equals?
You can clone your object and check equals

Can you change reference of Object?
You can extends your object class and add some checks in methods.

For serialization to JSON you can use GSON lib:
https://github.com/google/gson from google. After that you can check string equals

Maven dependency:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.1</version>
</dependency>

https://mvnrepository.com/artifact/com.google.code.gson/gson/2.8.1