[英]How do I compare objects in Java?
I have a data class written in Kotlin which has server error objects.我有一个用 Kotlin 编写的数据 class ,其中包含服务器错误对象。
How can I check which object it is?如何检查它是哪个 object?
I can do it in Kotlin like this我可以像这样在 Kotlin 中做到这一点
when (failure) {
is Failure.ServerError -> test()//do something
is Failure.ServerErrorConflict -> test()//do something
}
The same thing I want to do it in Java:我想在 Java 中做同样的事情:
switch (failure) {
case failure == Failure.ServerErrorConflict:
break;
}
But I get an error expression expected
但我得到一个expression expected
This is my data class这是我的数据 class
sealed class Failure {
object NetworkConnection : Failure()
object ServerError : Failure()
object ServerErrorConflict : Failure()
/** * Extend this class for feature specific failures.*/
abstract class FeatureFailure : Failure()
}
Please suggest how to do this.请建议如何做到这一点。
Generally in java, object references are compared to type using instanceof
binary operator.通常在 java、object 中,引用与使用instanceof
二元运算符的类型进行比较。
In future versions of Java, for some types, if-else conditions with instanceof
equality check is not needed and a switch can be used.在 Java 的未来版本中,对于某些类型,不需要具有instanceof
相等性检查的 if-else 条件,并且可以使用开关。 The sealed classes feature providing this benefit is being previewed currently in Java 15 , and being previewed again in the upcoming Java 16 .提供此好处的密封类功能目前正在 Java 15中进行预览,并在即将推出的 Java 16 中再次预览。
switch (failure) {
case NetworkConnection nc -> <do the required operation>
case ServerError se -> <do the required operation>
case ServerErrorConflict sec -> <do the required operation>
}
break
is not needed(will not fall through)不需要break
(不会失败)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.