简体   繁体   中英

Java - fire event when any property of object changes

In Java, what is the most elegant way for an object to fire an event whenever any property of an object changes?

My domain model has several objects like

class MyClass {

    String id;
    String name;
    Collection<MyThing> mythings= new HashSet<MyThing>();
    // more fields...
    Date lastUpdated;

    //constructor, getters and setters, etc
}

I need lastUpdated to be set to "today" whenever any of the properties (id/name/mythings) changes.

I would prefer a solution that is not JDO-specific, and definitely don't want this logic in the datastore (auto-timestamp column in the RDBMS etc).

I could put

this.lastUpdated = new Date();

in every setter, or fire a custom event in every setter, but that's ugly and error-prone.

Is there a more elegant solution?

You can implement the PropertyChangeListener interface and register your interest on the part of clients. It's been part of the Java Bean specification since 1.0.

They aren't all about UI elements. They were conceived as a way to match VB-like features for IDEs (eg the Bean Factory).

http://docs.oracle.com/javase/tutorial/uiswing/events/propertychangelistener.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM