【问题标题】:Switch cases for Interfaces接口的开关盒
【发布时间】:2020-02-06 09:15:01
【问题描述】:

有没有办法用switch语句判断一个特定的接口是否是instanceof另一个接口?

 MainInterface inter = //load interface

 switch (inter) {
        case instanceof Interface1:
            Interface1 inter1 = (Interface1) inter;
            //execute methods of inter1
        case instanceof Interface2:
            Interface2 inter2 = (Interface2) inter;
            //execute methods of inter2
    }

感谢您的帮助。

【问题讨论】:

  • 还没有,但正在考虑中。还有正在考虑的解构 if(obj instanceof Interface1 i1) { 至少会使 if / else if 不那么尴尬
  • 不,不直接。不过,您可以使用一个枚举值,您可以根据其类型从接口计算出该值。
  • @Ivar 不幸的是这对我没有帮助:(
  • @TryHard Non of the 23 answers?

标签: java interface switch-statement instanceof


【解决方案1】:

遗憾的是,这是不可能的,如 oracle 文档中所述:https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

开关适用于 byteshortcharint primitive 数据类型。它还适用于枚举类型 [...]、String 类和一些包装某些基本类型的特殊类:Character、Byte、Short 和 Integer [...]。

按照 Ivar 的建议,解决此问题的一些方法是使用 if-else 语句或实现子类型多态性。

【讨论】:

    【解决方案2】:

    使用 switch case 语句是不可能的。你必须使用 if 语句。

    MainInterface inter = null;
    
    if (inter instanceof Interface1) {
        Interface1 inter1 = (Interface1) inter;
        // execute methods of inter1
    } else if (inter instanceof Interface2) {
        Interface2 inter2 = (Interface2) inter;
        // execute methods of inter2
    }
    

    【讨论】:

    • 这是我目前的解决方案,但开关会更好看
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 2015-10-27
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多