Reputation: 79
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?
Upvotes: 2
Views: 6187
Reputation: 308763
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 (e.g the Bean Factory).
http://docs.oracle.com/javase/tutorial/uiswing/events/propertychangelistener.html
Upvotes: 1