Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using java.lang.Class<?> in a switch statement

Tags:

java

generics

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?

like image 311
Ali Avatar asked Jan 12 '23 02:01

Ali


1 Answers

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)
like image 162
rgettman Avatar answered Jan 19 '23 11:01

rgettman