Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java have property observers similar to Swift's willSet & didSet methods?

I want to observe whether a variable's value has been changed. I was wondering if Java has something that is equivalent to the willSet and didSet methods in Swift?

like image 848
Thor Avatar asked Feb 23 '16 23:02

Thor


People also ask

What are property observer in Swift?

Property observers observe and respond to changes in a property's value. Property observers are called every time a property's value is set, even if the new value is the same as the property's current value. You can add property observers in the following places: Stored properties that you define.

What is willSet in Swift?

willSet is called before the data is actually changed and it has a default constant newValue which shows the value that is going to be set. didSet is called right after the data is stored and it has a default constant oldValue which shows the previous value that is overwritten.


1 Answers

Not as a language. Java on its own does not really know properties of any kind. What you can do, though:

  1. If the object is yours, just change your setter. That's why they're in the first place.
  2. If that is not good enough for you and you want something better, at least I hope you have Java 8. In there, you can use JavaFX's properties: e.g. the LongProperty.
  3. If you can't change the code, you'll have to go for AOP.
like image 180
Petr Janeček Avatar answered Nov 06 '22 04:11

Petr Janeček