Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Getters: Always execute specific method

Is there a way to define a method, which is called everytime I call a get?

I have an Object Contact and don't want to set updateLastUsed(); in about 30 Getters for my Members.

like image 635
Henrik P. Hessel Avatar asked Feb 12 '26 16:02

Henrik P. Hessel


2 Answers

Instead of accessing the getter for your properties, you could create one general getter that takes the property name as an input. The return type would need to be Object if your properties are of different types.

In this general getter you call the property getter and the updateLastUsed() method. To be safe make all property getters private.

like image 171
Johannes Avatar answered Feb 15 '26 04:02

Johannes


I would have suggested AOP but if it's J2ME we're talking about you're most likely better off manually inserting "onGetCalled()" in each of your 30 accessors and then coding whatever you need within that method. You may want to pass in name of the method being called (or property accessed) in case you need it in the future.

like image 36
ChssPly76 Avatar answered Feb 15 '26 04:02

ChssPly76



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!