【问题标题】:How can I use class type with switch in java?java - 如何在java中使用带有switch的类类型?
【发布时间】: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 块,但此时我的好奇心更多。谢谢。

【问题讨论】:

标签: java class switch-statement


【解决方案1】:

Java Language Specification 声明,对于switch 语句的表达式

Expression的类型必须是char、byte、short、int、Character、Byte、 Short、Integer、String 或枚举类型,或发生编译时错误。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      您不能使用switch 语句来比较对象的类类型。您将不得不接受if-else 声明。

      【讨论】:

        猜你喜欢
        • 2011-02-28
        • 1970-01-01
        • 2012-04-27
        • 1970-01-01
        • 1970-01-01
        • 2021-01-17
        • 1970-01-01
        • 1970-01-01
        • 2021-02-04
        相关资源
        最近更新 更多