如何在java中使用带开关的类类型?

时间:2014-04-09 02:28:11

标签: java class switch-statement

我有以下代码:

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...
}

当我输入代码时,我得到一个错误,说&#34;期望Integer.class常量表达式&#34;。我想使用一个开关块,因为键入更清楚:

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

我很困惑为什么if块在没有错误的情况下编译而没有错误。我并不完全反对使用if块,但这在很大程度上取决于我的好奇心。感谢。

3 个答案:

答案 0 :(得分:2)

Java Language Specification表示对于switch语句的表达式

  

Expression的类型必须是char,byte,short,int,Character,Byte,   短,整数,字符串或枚举类型,或发生编译时错误。

答案 1 :(得分:0)

您不能使用switch语句。 switch case标签只能使用整数值,字符串或枚举。

答案 2 :(得分:0)

您不能使用switch语句来比较对象的类类型。您必须使用if-else语句。

相关问题