Java Reference
In-Depth Information
When the user makes a change in the common frame, all the observers are notified. The
notification is sent to the method with the signature public void update(Observable o, Object
arg) . In that method, we first confirm that we did receive an instance of the OptionUpdate
value object, and if not we ignore the entire message. If it is an OptionUpdate , then we recast it
so that we can easily get access to information about what has changed, as shown in the fol-
lowing code snippet:
if (! (arg instanceof OptionUpdate)) {
log.log(Level.WARNING,
"DatabaseLocationDialog received update type: " + arg,
new IllegalArgumentException());
return;
}
OptionUpdate optionUpdate = (OptionUpdate) arg;
Caution You should always check for nulls or for the type of an object before recasting it. However, if you
check the type of the object, you may not need to explicitly check for null since instanceof will return false
if passed a null reference. You should also check for nulls being passed into any API you have made public.
Even though we know that the class we are currently observing should only send us instances of the
OptionUpdate class, we cannot guarantee that this will never change in the future. Should this change,
we will get a warning log message giving as much information on what has been received and where it
came from as possible.
Tip Even though we created an IllegalArgumentException for the purposes of creating a stack trace
in the log message, we never threw it, so the application will continue to run. Creating an exception simply
for the information available from the exception can be a useful tool if you ever need to debug your code.
Note It may not be desirable to log all updates received that your particular code is not interested in.
When AWT was first released, all events would be sent to any class that was interested in any event. This
could mean that a class that was only interested in learning when the mouse moved over a particular field
might get millions of updates as the mouse moved over other areas of the screen—in such a case you
would not want to log all the unwanted events. However, in this particular case where we know all the
events that can be generated at this time, it makes sense to log a warning if we receive an event we were
not expecting.
Search WWH ::




Custom Search