java Field change listener

2019-09-15 21:08发布

问题:

So I would really want some way of detecting Field changes of a certain object. I have googled for quite a while but haven't found anything. So basically all I need to know, is when some variable of a object changed. lets take this class for instance:

public class Example{
    String text = "test";

    public static void main(String[] args){
        Example e = new Example();
        e.text = "something else";
    }
}

I would basically want to detect when the 'text' variable has changed. I know many of you would say use getters and setters and such, this is not what I want though.

For a reason I can't easily explain, I need to be able to detect the field change from outside the class. Currently I am thinking of using a second thread that basically just scans a list of objects continuously and use reflection to detect changes that way, but that will obviously make the program heavier than it has to be.

So I hope there is a way of just creating listeners for field changes, does anyone know about libraries/systems/methods to do this?

回答1:

Let's bring this back to life :)

There are several approaches:

The first one, which I believe works like since Java 6, is to use Bound Properties inside Java Beans (yes, it also works in JavaSE).

A bound property notifies listeners when its value changes. This has two implications:

The bean class includes addPropertyChangeListener() and removePropertyChangeListener() methods for managing the bean's listeners. When a bound property is changed, the bean sends a PropertyChangeEvent to its registered listeners. PropertyChangeEvent and PropertyChangeListener live in the java.beans package.

The java.beans package also includes a class, PropertyChangeSupport, that takes care of most of the work of bound properties. This handy class keeps track of property listeners and includes a convenience method that fires property change events to all registered listeners.

In the second, you get most of the things for free, its on Java 7 (javafx 2.0), and it's called JavaFX Properties.

You can also add a change listener to be notified when the property's value has changed, as shown in You can also add a change listener to be notified when the property's value has changed.

The downside of the latter is that JPA is not friendly with this, so its a bit of a pain to get it running.