Java IF-ELSE语句的替代项,用于强制转换对象实例



我有这个代码:

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中还没有这样的语法。你可以试试Kotlin,它已经支持这个:

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

正如@Progman所指出的,这个问题和其他问题类似,你也应该去看看。

最新更新