我可以用 java bean 抛出异常吗

Can I throw exception with java bean

我想通知 class1 可以或不能更改变量的异常。我试图放入 propertyChange 以抛出异常,但我不能使用此方法。我如何通知 class1?

class1 ->

public void setProperty(int var) {
    if(var > 0){
    propertySupport.firePropertyChange("var", this.var,var);
    this.var = var;
    }else{
       System.out.println("bla bla"); 
    }
}

//methods
public void addPropertyChangeListener(PropertyChangeListener listener) {
    propertySupport.addPropertyChangeListener(listener);
}

public void removePropertyChangeListener(PropertyChangeListener listener) {
    propertySupport.removePropertyChangeListener(listener);
}

class2 ->

@Override
public void propertyChange(PropertyChangeEvent evt){
    if(evt.getNewValue().equals("var"))
       //TODO
    }else{
       //throw exception to not change var in class1
    }

您需要使用 VetoableChangeListener

参见JavaDoc

public interface VetoableChangeListener extends EventListener

A VetoableChange event gets fired whenever a bean changes a "constrained" property. You can register a VetoableChangeListener with a source bean so as to be notified of any constrained property updates.

void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException

This method gets called when a constrained property is changed.

Parameters: evt - a PropertyChangeEvent object describing the event source and the property that has changed. Throws: PropertyVetoException - if the recipient wishes the property change to be rolled back.

FirePropertyChange 会告诉我更改我有兴趣使用的变量或属性。您应该验证是否在同一 "setProperty" 方法中更改变量,然后通知 class 2 该值已更改

class1

public void setProperty(int var) {

if(this.var != var && var > 0){
   propertySupport.firePropertyChange("var", this.var,var);
   this.var = var;
}else{
   System.out.println("bla bla"); 
}

}

class2

@Override
public void propertyChange(PropertyChangeEvent evt){
if(evt.getPropertyName().equals("var")){

   //I do something with this new variable
   System.out.print(evt.getNewValue());
}else{
   //throw exception to not change var in class1
}