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

2

8

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?

Ran answered 4/3, 2014 at 23:52 Comment(1)
Extract the class name String and switch on that.Horme
L
13

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)
Leith answered 4/3, 2014 at 23:55 Comment(5)
Can I still do a normal == comparison, like if type == FooType.class in the above code, where type is Class<? extends FooBase> and FooType implements FooBase?Ran
Yes, you can compare Class objects directly.Leith
In many cases what you really want to use when testing types is instanceof rather than ==.Evacuation
@Evacuation Only for testing if an object is an instance of a class, not whether Class objects are the same.Leith
isAssignableFrom can be used to tell whether a class is "equal to or a subclass" of another, like instanceof but without needing an object.Plumbism
H
0

What about something like this :

String result = switch (String.valueOf(type)) {
    case "class xx.xx.FooBase" ->     "This is a FooBase";
    case "class java.lang.Number" ->  "This is a Number";
    case "class java.lang.Boolean" -> "This is a Boolean";
    case "class java.lang.String" ->  "This is a String";
    case null, default -> throw new IllegalArgumentException();
}

I'm using Java 21.

Hope it'll help someone.

Heavyhanded answered 17/5, 2024 at 8:52 Comment(2)
If you are using Java 21, perhaps JEP 441 is more appropriate?Hekker
By converting the variable type (Class<?>) to Object, it's better indeed.Heavyhanded

© 2022 - 2025 — McMap. All rights reserved.