ilansch ilansch - 1 month ago 6
Java Question

Can you use a switch statement on Class values?

My goal is to make exception thrower. I want to be able to call something like

exThrower.Throw<UsernameDuplicatedException>("someUserId");


and have it throw an exception.

So I created
ExceptionThrower
class as:

public class ExceptionsThrower {
public static <T extends Exception> void throwException(Class<T> exceptionType, String[] params) throws Exception {
if (exceptionType == UsernameDuplicatedException.class) {
throw new UsernameDuplicatedException(params[0]);
}

switch(exceptionType) {
case UsernameDuplicatedException.class: // This does not compile: "expects Class<T> and find Class<..UsernameDuplicatedException>"
throw new UsernameDuplicatedException(params[0]);
}
};
}

@ResponseStatus(HttpStatus.CONFLICT)
class UsernameDuplicatedException extends RuntimeException {

public UsernameDuplicatedException(String email) {
super(email + " already exist!");
}
}


But the
switch
statement doesn't compile. The compiler produces an error similar to

error: constant expression required
case UsernameDuplicatedException.class:
^


Can we not use a
switch
statement with
Class
values?

Answer

It doesn't compile because a Class is not part of the supported types in a switch statement see §14.11 of the Java Language Specification:

SwitchStatement:
    switch ( Expression ) SwitchBlock

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.

Comments