Strings in Switch .. and classes

Jonathan Gibbons Jonathan.Gibbons at Sun.COM
Wed Dec 16 12:17:16 PST 2009


Paul Benedict wrote:
> 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
>
>   


Setting aside issues of class identity, the proposed desugaring does not 
take the use of subtypes into account.

-- Jon



More information about the coin-dev mailing list