需要在属性更改时调用的方法

时间:2013-11-13 16:15:52

标签: java class attributes

我在Java类中有一个属性,当Java类中的属性改变它的值时,我需要在同一个类中调用一个方法。我怎么能这样做?

 boolean setInstallMode = false;

 public void callMeWhenChanged() {

    some actions . . . 

 }

4 个答案:

答案 0 :(得分:3)

setInstallMode设为私有,然后只通过setter方法设置它。

private boolean installMode = false;

public void setInstallMode(boolean mode)
{
    installMode = mode;
    callMeWhenChanged();
}

public void callMeWhenChanged() {

   some actions . . . 

}

答案 1 :(得分:1)

您可以将属性设为private,然后为该属性设置setAttribute方法,然后在该set属性方法中调用callMeWhenChanged

private boolean installMode

public void setInstallMode(boolean o){
    this.installMode = o;
    callMeWhenChanged()
    //WhateverElse
}

答案 2 :(得分:0)

 private   boolean setInstallMode = false; // Make attribute as private field

 public void setInstallMode(boolean inBooleanValue){ // write public mutator for this attribute 
  this.setInstallMode =inBooleanValue; // update value

   callMeWhenChanged();// Call your logic
  }


 public void callMeWhenChanged() {

    some actions . . . 

 }

答案 3 :(得分:0)

您可以使用属性更改侦听器,如下例所示:

http://examples.javacodegeeks.com/core-java/beans/bean-property-change-event-listener/