【问题标题】:Alternative to Java IF-ELSE statement for casting object instances [closed]用于转换对象实例的 Java IF-ELSE 语句的替代方法 [关闭]
【发布时间】:2020-10-22 19:03:43
【问题描述】:

我有这个代码:

entity.conditions().forEach(entityCondition - > {
    if (entityCondition instanceof LinkCondition) {
        LinkCondition condition = (LinkCondition) entityCondition;
    } else if (entityCondition instanceof OppositeLinkCondition) {
        //...
    } else if (entityCondition instanceof PropertyEqualCondition) {
        //...
    } else if (entityCondition instanceof PropertyLocalTimeRangeCondition) {
        //...      
    }
    // and 20 or so, more conditions...
});

在其中我正在寻找一种替代 IF-ELSE 语句的方法,一种更优雅的方法来处理数十个instanceof 条件。

【问题讨论】:

标签: java


【解决方案1】:

不幸的是,Java 中还没有这样的语法。您可以尝试已经支持此功能的 Kotlin:

val b = when (a) {
    is String -> a.length
    is Int -> a
    is Long -> (a and 0xFFFFFFFF).toInt()
    else -> a.hashCode()
}    

正如@Progman 指出的,这个问题与其他问题类似,你也应该检查一下。

【讨论】:

    猜你喜欢
    • 2018-03-29
    • 2016-10-15
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 2014-11-29
    • 2010-12-09
    • 2014-05-22
    • 1970-01-01
    相关资源
    最近更新 更多