【发布时间】:2014-04-09 02:28:10
【问题描述】:
我有以下代码:
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...
}
当我输入代码时,我收到一条错误消息,提示“需要 Integer.class 常量表达式”。我想使用一个 switch 块,因为它打字更干净:
if (var.type == Integer.class) {}
我很困惑为什么 if 块会编译而没有错误,而 switch 块不会。我并不完全反对使用 if 块,但此时我的好奇心更多。谢谢。
【问题讨论】:
-
if条件与case标签具有不同的属性。
标签: java class switch-statement