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?
Asked
Active
Viewed 2,803 times
8
-
Are you using objects? – Ceelos Feb 23 '16 at 23:49
-
Just variable in general, could be string, int, or instance of classes that I came up with myself. – Thor Feb 23 '16 at 23:59
-
Please only tag questions with the language that the question is actually about. – nhgrif Feb 24 '16 at 00:00
-
This might help you: http://stackoverflow.com/questions/12386604/how-to-watch-a-variable-for-changes. Seems like the answer is a no. – Ceelos Feb 24 '16 at 00:08
1 Answers
6
Not as a language. Java on its own does not really know properties of any kind. What you can do, though:
- If the object is yours, just change your setter. That's why they're in the first place.
- 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
. - If you can't change the code, you'll have to go for AOP.

Petr Janeček
- 37,768
- 12
- 121
- 145