Strings in Switch .. and classes
Paul Benedict
pbenedict at apache.org
Wed Dec 16 10:29:09 PST 2009
It occurred to me that if hashCode() really is an acceptable and
fool-proof (yet to be convinced) way to implement strings in switch,
this potentially opens a further enhancement to switch on Class.
Perhaps in JDK 8, we could convert many instanceof checks into label
cases.
Class c = o.getClass();
if (c instanceof String) { .. }
else if (c instanceof Integer) { ..}
else if (c instanceof Date) { .. }
Can be de-sugared into the new String switch:
switch (object.getClass().getName()) {
case "java.lang.String":
case "java.lang.Integer":
case "java.util.Date":
}
}
PS: Since instanceof evaluates null to false, as like any other switch
statement, an if-check should still be done in front lest an NPE
occurs.
Paul
More information about the coin-dev
mailing list