bula
bula

Reputation: 9429

Call a method on change of a value

There is a variable called age,

int static age = 21;

I want to call method

onAgeIncreased(){
    ........... something......
}

whenever the age is changed by any thread in my program (Just like in event driven programming). Can I get it done with java?

Upvotes: 0

Views: 362

Answers (3)

zbig
zbig

Reputation: 3956

You can achieve this by sticking to JavaBeans convention and implement PropertyChangeListener that be listening whenever the value changed. You can also utilize PropertyChangeSupport that is thread safe. Withing a Javadoc of it you can find a very nice example that will suits your needs.

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

Doing this in Java. You can use getter and setter.

public class MyTest{
 private static int age = 21;

 public void setAge(int age){
   this.age=age;
 }

 public int getAge(){
   return  age;
 }
}

When ever you want to change the age, you can use setAge(int newAge) method to change age, Then when ever you want to get age back just call getAge()

Upvotes: 0

ToasteR
ToasteR

Reputation: 888

You could change the variable via a setter method and do stuff there.

Upvotes: 1

Related Questions