Simple Question: ValueChanged Event in Java

前端 未结 3 966
南旧
南旧 2021-01-26 01:53

Is there an event in Java that fires when a value changes? Like in this example

public class Example{
    public String var1 = \"Something\";
    public Int var2         


        
3条回答
  •  余生分开走
    2021-01-26 02:29

    The answer is not to expose your fields publicly to start with. Make the fields private, introduce getter and setter methods, and you can call whatever you like within the setter if the value's changed.

    public class Example {
        private String var1 = "Something";
    
        public String getVar1() {
            return var1;
        }
    
        public void setVar1(String var1) {
            // TODO: null guards
            if (var1.equals(this.var1)) {
                // No-op - no need to do anything
                return;
            }
            this.var1 = var1;
            notifyListenersOfChangeToVar1();
        }
    }
    

提交回复
热议问题