I'm trying to use a Class<?>
in an if statement, like the following:
public static Model get(Class<? extends FooBase> type, long id )
{
switch (type)
{
case FooType.class:
return new Foo(id);
break;
}
}
However, the line: case FooType.class:
is giving me the error,
Expected Class<capture<? extends FooBase>> , given Class<FooType.class>
.
FooType
does implement the FooBase
interface.
Is it not possible to do a switch on Class<?>
values?
You cannot use a Class
as the expression for your switch statement, according to the JLS, Section 14.11:
The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (§8.9), or a compile-time error occurs.
You can compare the Class
objects directly. Because there is only one Class
object per actual class, the ==
operator works here.
if (type == FooType.class)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With