Class CompareBuilder

java.lang.Object
org.aoju.bus.core.builder.CompareBuilder
All Implemented Interfaces:
Serializable, Builder<Integer>

public class CompareBuilder extends Object implements Builder<Integer>
用于构建 Comparable.compareTo(Object) 方法的辅助工具 在Bean对象中,所有相关字段都参与比对,继承的字段不参与 使用方法如下:
 public class MyClass {
   String field1;
   int field2;
   boolean field3;

   ...

   public int compareTo(Object o) {
     MyClass myClass = (MyClass) o;
     return new CompareToBuilder()
       .appendSuper(super.compareTo(o)
       .append(this.field1, myClass.field1)
       .append(this.field2, myClass.field2)
       .append(this.field3, myClass.field3)
       .toComparison();
   }
 }
 

字段值按照顺序比较,如果某个字段返回非0结果,比较终止,使用toComparison()返回结果,后续比较忽略

也可以使用reflectionCompare 方法通过反射比较字段,使用方法如下:

 public int compareTo(Object o) {
     return CompareToBuilder.reflectionCompare(this, o);
 }
 
Since:
Java 17+
Author:
Kimi Liu
See Also: