Reputation: 5739
Up to this point, I have used the following code to restrict the application of some methods to instances of certain classes. For instance, using ItemListener
, but this could be applied to many things,
public class mListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
if (!(e.getItemSelectable instanceof JCheckBox)) { //again, JCheckBox was chosen arbirtarily
System.err.println("mListener can only be applied to a JCheckBox");
return;
}
}
}
However, in a few places on the Oracle Java tutorials, I have seen the following code
public class mListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
JCheckBox box = null;
try {
box = (JCheckBox) e.getItemSelectable();
} catch (ClassCastException ex) {
System.err.println("mListener can only be applied to a JCheckBox");
return;
}
}
}
Which is the best way to lock out classes that you don't want a method applied to? This is especially the case with implementing interfaces, where the parameter can't be changed.
Upvotes: 1
Views: 91
Reputation: 5739
The answer may be this: catching a ClassCastException
allows e
to be any subclass of JCheckBox
, whereas using instanceof restricts it solely to a JCheckBox
.
Upvotes: 0
Reputation: 1503020
In both cases, this is a programming error. The listener is being added inappropriately. The correct response for this is almost certainly not just printing out a message where it will probably never be seen - it's an exception.
Simply casting will give you that exception without any work on your part, so just cast unconditionally, and don't try to cover up programming errors.
Upvotes: 6
Reputation: 299138
The second version is evil, as it uses exceptions for flow control. Read Effective Java by Joshua Bloch to learn why that is bad (Item 57: "Use exceptions only for exceptional conditions").
Upvotes: 3