比较两个对象(不包括某些字段) - Java

Ana*_*tel 9 java equality class equals

我需要比较同一类的两个对象(不包括某些字段)。

public final class Class1 {
  private String a;
  private String b;
  private String c;
:
:
:

  private String z;
  private Date createdAt; 
  private Date updatedAt; 
} 
Run Code Online (Sandbox Code Playgroud)

我怎样才能找到上述类的两个对象是否相等(不包括createdAt和updatedAt值)?由于这个类中有很多字段,我不想一一比较。

请不要提供 AssertJ 的递归比较解决方案,因为我不需要它进行单元测试。

先感谢您!

Ren*_*235 8

无需编写任何代码的最快方法是Lombok

Lombok 是 Java 中最常用的库之一,它从您的项目中删除了大量的样板代码。如果您需要了解更多有关它的功能和用途的信息,请转到此处

实现您需要的方法非常简单:

// Generate the equals and HashCode functions and Include only the fields that I annotate with Include
@EqualsAndHashCode(onlyExplicitlyIncluded = true) 
@Getter // Generate getters for each field
@Setter // Generate setters for each field
public class Class1
{

  @EqualsAndHashCode.Include // Include this field
  private Long identity;
  
  private String testStr1; // This field is not annotated with Include so it will not be included in the functions.

  // ... any other fields
}
Run Code Online (Sandbox Code Playgroud)

Lombok 能做的远不止这些。有关更多信息,请@EqualsAndHashCode参阅

您始终可以使用@EqualsAndHashCode.Exclude以下方法更快地解决您的用例:

@EqualsAndHashCode
@Getter // Generate getters for each field
@Setter // Generate setters for each field
public final class Class1 {
  private String a;
  private String b;
  private String c;
:
:
:

  private String z;

  @EqualsAndHashCode.Exclude
  private Date createdAt; 
  @EqualsAndHashCode.Exclude
  private Date updatedAt; 
} 
Run Code Online (Sandbox Code Playgroud)


Tur*_*g85 7

如果重写Object::equalsandObject::hashCode不是一个选项,我们可以使用ComparatorAPI来构造相应的比较器:

final Comparator<Class1> comp = Comparator.comparing(Class1::getA)
        .thenComparing(Class1::getB)
        .thenComparing(Class1::getC)
        .
        .
        .
        .thenComparing(Class1::getZ);
Run Code Online (Sandbox Code Playgroud)

不幸的是,如果不比较所有应该相等的字段,就无法做到这一点。