Java:等于检查接口(interface)而不是类

标签 java interface equals

我有一个案例,其中我有一个代表实体的 Java 接口(interface)。该接口(interface)在两个不同的类中实现。 因此,我需要一种测试方法 - 如果两个类有一个公共(public)接口(interface) - 如果这两个类的所有 Getter 值都相同

如果两者都为真,那么在我需要的情况下它们是相等的。 (注意,我不知道他们实现了哪个接口(interface),有几种可能)

这是否可能,或者我是否需要提供接口(interface),然后检查两个类是否实现它?

感谢您的帮助, 迈克尔

最佳答案

注意:如果一个类有不同的接口(interface),那么这可能会破坏约束:

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.

@see:Object.equals 的 java 文档

如果你有三个 A、B、C 类树 Itnerfaces I1、I2、I3:

  • A 实现接口(interface) I1 和 I2,
  • B 实现 I2 和 I3
  • C 实现 I1 和 I3。

那么你可能会遇到这样的情况:

  • 由于 I2,A 等于 B
  • 由于 I3,B 等于 C
  • 但是:由于 I3,A 不等于 C

这会违反传递约束!这可能会导致难以发现的错误!

这只是一个警告,在开始将其声明为主要架构风格之前要三思。

已添加:

相反,我建议实现类似于比较器的东西,但不是比较而是检查“等于”,其含义类似于“等于 X”(其中 X 是您的接口(interface))

关于Java:等于检查接口(interface)而不是类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4736293/

相关文章:

java - 使用哪种语言来创建此桌面应用程序?

java - 引用配置管理工厂创建的 OSGi 服务

c# - 强制接口(interface)属性的返回值可序列化

java - 具有相同哈希码的两个不相等的对象

java - 获取 javax.net.ssl.SSLProtocolException : end of file

testing - 如果直接访问其字段,如何模拟结构

objective-c - 是否需要在@interface 中声明ivars 来匹配属性?

java - 等于重写 String 和 Int

java - 替代 String.equals 进行多次比较(无枚举)

java - 如何增加 ExtentReports 4.0.9 中屏幕截图缩略图的大小