Java observer update function
•
Java
I have a class that implements the observer. Of course, it needs to have the update function:
public void update(Observable obs,Object obj);
Can someone explain what these two parameters represent? Observable is of course my observable object, but how can I access my observable field through this observable OBS object? What is object obj?
Solution
If others have trouble determining how to send the second parameter, as Nick pointed out: in the notifyobservers method call
In observable:
private void setLicenseValid(boolean licenseValid) { this.licenseValid = licenseValid; setChanged(); // update will only get called if this method is called notifyObservers(licenseValid); // add parameter for 2nd param,else leave blank }
In the observer:
@Override public void update(Observable obs,Object arg) { if (obs instanceof QlmLicense) { setValid((Boolean) arg); } }
Please connect observable correctly, otherwise your update method will not be called
public class License implements Observer { private static QlmLicense innerlicense; private boolean valid; private Observable observable; private static QlmLicense getInnerlicense() { if (innerlicense == null) { innerlicense = new QlmLicense(); // This is where we call the method to wire up the Observable. setObservable(innerlicense); } return innerlicense; } public boolean isValid() { return valid; } private void setValid(Boolean valid) { this.valid = valid; } // This is where we wire up the Observable. private void setObservable(Observable observable) { this.observable = observable; this.observable.addObserver(this); } @Override public void update(Observable obs,Object arg) { if (obs instanceof InnerIDQlmLicense) { setValid((Boolean) arg); } } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码