我有以下代码:
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块,但这在很大程度上取决于我的好奇心。感谢。
答案 0 :(得分:2)
Java Language Specification表示对于switch
语句的表达式:
Expression的类型必须是char,byte,short,int,Character,Byte, 短,整数,字符串或枚举类型,或发生编译时错误。
答案 1 :(得分:0)
您不能使用switch
语句。 switch
case
标签只能使用整数值,字符串或枚举。
答案 2 :(得分:0)
您不能使用switch
语句来比较对象的类类型。您必须使用if-else
语句。