guyfleeman
guyfleeman

Reputation: 473

How can I use class type with switch in java?

I have the following code:

Variable var;
//var is initialized to an unknown class type, stored as a public variable named type.
//var = new Variable<Integer>(Integer.class, <some integer value>);
//var.type is equal to Integer.class

switch (var.type)
{
case Integer.class:
    //do some class specific stuff 
    break;
case Float.class:
    //do some class specific stuff
    break;
etc...
}

When I type the code out I get an error saying "Integer.class constant expression expected". I would like to use a switch block because it is cleaner that typing out:

if (var.type == Integer.class) {}

I am confused as to why the if block will compile without error while the switch block will not. I'm not entirely against using if blocks but its more a matter of my curiosity at this point. Thanks.

Upvotes: 1

Views: 2748

Answers (3)

cybersam
cybersam

Reputation: 66999

The Java Language Specification states that, for a switch statement's Expression:

The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type, or a compile-time error occurs.

Upvotes: 3

Muhammad Kashif Nazar
Muhammad Kashif Nazar

Reputation: 23865

You cannot use a switch statement to compare class type of an object. You would have to live with if-else statements.

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279970

You cannot use a switch statement for this. Only integer values, strings or enums can be used with switch case labels.

Upvotes: 0

Related Questions