As part of an investigation into the parameters of a method, I tried the new Pattern Matching for switch (Preview). Using a traditional condition, it works perfectly:
Method firstMethod = BitSet.class.getDeclaredMethods()[0];
Parameter firstParameter = firstMethod.getParameters()[0];
if (firstParameter.getType() == Integer.class) {
System.out.println("Integer");
}
When I tried to refactor it to use a switch
statement, it did not compile:
Method firstMethod = BitSet.class.getDeclaredMethods()[0];
Parameter firstParameter = firstMethod.getParameters()[0];
switch (firstParameter.getType()) {
case Integer.class: System.out.println("Integer");
case int.class: System.out.println("int");
default: System.out.println("other");
}
The error is:
error: incompatible types: Class<Integer> cannot be converted to Class<CAP#1>
case Integer.class: System.out.println("Integer");
^
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?
Is this something that can't be done, or is it just a syntax error?
This is not how switching over types work. You can switch over an object’s actual type and have to specify type names, rather than
Class
literals.Note that with pattern matching, there is no fall-through support, so specifying
break
is mandatory. Or you use the new syntax which has no fall-through in the first placeThe object returned by
getType()
is always an instance ofjava.lang.Class
, so branching by its type makes no sense. This doesn’t mean that comparing the actual values with aswitch
statement or expression was impossible. The comparison can be performed with a guarded pattern:Note that the JDK 17 preview used
&&
instead ofwhen
but that’s only for completeness. I think it’s obvious that this is no improvement over
if
statements or a map fromClass
to handler.