All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.hutool.core.builder.CompareToBuilder Maven / Gradle / Ivy

There is a newer version: 5.8.33
Show newest version
package cn.hutool.core.builder;

import cn.hutool.core.util.ArrayUtil;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.Comparator;

/**
 * 用于构建 {@link java.lang.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结果,比较终止,使用{@code toComparison()}返回结果,后续比较忽略。 * *

* 也可以使用{@link #reflectionCompare(Object, Object) reflectionCompare} 方法通过反射比较字段,使用方法如下: * *

 * public int compareTo(Object o) {
 *   return CompareToBuilder.reflectionCompare(this, o);
 * }
 * 
* *TODO 待整理 * 来自于Apache-Commons-Lang3 * @author looly,Apache-Commons * @since 4.2.2 */ public class CompareToBuilder implements Builder { private static final long serialVersionUID = 1L; /** 当前比较状态 */ private int comparison; /** * 构造,构造后调用append方法增加比较项,然后调用{@link #toComparison()}获取结果 */ public CompareToBuilder() { comparison = 0; } //----------------------------------------------------------------------- /** * 通过反射比较两个Bean对象,对象字段可以为private。比较规则如下: * *
    *
  • static字段不比较
  • *
  • Transient字段不参与比较
  • *
  • 父类字段参与比较
  • *
* *

*如果被比较的两个对象都为null,被认为相同。 * * @param lhs 第一个对象 * @param rhs 第二个对象 * @return a negative integer, zero, or a positive integer as lhs * is less than, equal to, or greater than rhs * @throws NullPointerException if either (but not both) parameters are * null * @throws ClassCastException if rhs is not assignment-compatible * with lhs */ public static int reflectionCompare(final Object lhs, final Object rhs) { return reflectionCompare(lhs, rhs, false, null); } /** *

Compares two Objects via reflection.

* *

Fields can be private, thus AccessibleObject.setAccessible * is used to bypass normal access control checks. This will fail under a * security manager unless the appropriate permissions are set.

* *
    *
  • Static fields will not be compared
  • *
  • If compareTransients is true, * compares transient members. Otherwise ignores them, as they * are likely derived fields.
  • *
  • Superclass fields will be compared
  • *
* *

If both lhs and rhs are null, * they are considered equal.

* * @param lhs left-hand object * @param rhs right-hand object * @param compareTransients whether to compare transient fields * @return a negative integer, zero, or a positive integer as lhs * is less than, equal to, or greater than rhs * @throws NullPointerException if either lhs or rhs * (but not both) is null * @throws ClassCastException if rhs is not assignment-compatible * with lhs */ public static int reflectionCompare(final Object lhs, final Object rhs, final boolean compareTransients) { return reflectionCompare(lhs, rhs, compareTransients, null); } /** *

Compares two Objects via reflection.

* *

Fields can be private, thus AccessibleObject.setAccessible * is used to bypass normal access control checks. This will fail under a * security manager unless the appropriate permissions are set.

* *
    *
  • Static fields will not be compared
  • *
  • If compareTransients is true, * compares transient members. Otherwise ignores them, as they * are likely derived fields.
  • *
  • Superclass fields will be compared
  • *
* *

If both lhs and rhs are null, * they are considered equal.

* * @param lhs left-hand object * @param rhs right-hand object * @param excludeFields Collection of String fields to exclude * @return a negative integer, zero, or a positive integer as lhs * is less than, equal to, or greater than rhs * @throws NullPointerException if either lhs or rhs * (but not both) is null * @throws ClassCastException if rhs is not assignment-compatible * with lhs * @since 2.2 */ public static int reflectionCompare(final Object lhs, final Object rhs, final Collection excludeFields) { return reflectionCompare(lhs, rhs, ArrayUtil.toArray(excludeFields, String.class)); } /** *

Compares two Objects via reflection.

* *

Fields can be private, thus AccessibleObject.setAccessible * is used to bypass normal access control checks. This will fail under a * security manager unless the appropriate permissions are set.

* *
    *
  • Static fields will not be compared
  • *
  • If compareTransients is true, * compares transient members. Otherwise ignores them, as they * are likely derived fields.
  • *
  • Superclass fields will be compared
  • *
* *

If both lhs and rhs are null, * they are considered equal.

* * @param lhs left-hand object * @param rhs right-hand object * @param excludeFields array of fields to exclude * @return a negative integer, zero, or a positive integer as lhs * is less than, equal to, or greater than rhs * @throws NullPointerException if either lhs or rhs * (but not both) is null * @throws ClassCastException if rhs is not assignment-compatible * with lhs * @since 2.2 */ public static int reflectionCompare(final Object lhs, final Object rhs, final String... excludeFields) { return reflectionCompare(lhs, rhs, false, null, excludeFields); } /** *

Compares two Objects via reflection.

* *

Fields can be private, thus AccessibleObject.setAccessible * is used to bypass normal access control checks. This will fail under a * security manager unless the appropriate permissions are set.

* *
    *
  • Static fields will not be compared
  • *
  • If the compareTransients is true, * compares transient members. Otherwise ignores them, as they * are likely derived fields.
  • *
  • Compares superclass fields up to and including reflectUpToClass. * If reflectUpToClass is null, compares all superclass fields.
  • *
* *

If both lhs and rhs are null, * they are considered equal.

* * @param lhs left-hand object * @param rhs right-hand object * @param compareTransients whether to compare transient fields * @param reflectUpToClass last superclass for which fields are compared * @param excludeFields fields to exclude * @return a negative integer, zero, or a positive integer as lhs * is less than, equal to, or greater than rhs * @throws NullPointerException if either lhs or rhs * (but not both) is null * @throws ClassCastException if rhs is not assignment-compatible * with lhs * @since 2.2 (2.0 as reflectionCompare(Object, Object, boolean, Class)) */ public static int reflectionCompare( final Object lhs, final Object rhs, final boolean compareTransients, final Class reflectUpToClass, final String... excludeFields) { if (lhs == rhs) { return 0; } if (lhs == null || rhs == null) { throw new NullPointerException(); } Class lhsClazz = lhs.getClass(); if (!lhsClazz.isInstance(rhs)) { throw new ClassCastException(); } final CompareToBuilder compareToBuilder = new CompareToBuilder(); reflectionAppend(lhs, rhs, lhsClazz, compareToBuilder, compareTransients, excludeFields); while (lhsClazz.getSuperclass() != null && lhsClazz != reflectUpToClass) { lhsClazz = lhsClazz.getSuperclass(); reflectionAppend(lhs, rhs, lhsClazz, compareToBuilder, compareTransients, excludeFields); } return compareToBuilder.toComparison(); } /** *

Appends to builder the comparison of lhs * to rhs using the fields defined in clazz.

* * @param lhs left-hand object * @param rhs right-hand object * @param clazz Class that defines fields to be compared * @param builder CompareToBuilder to append to * @param useTransients whether to compare transient fields * @param excludeFields fields to exclude */ private static void reflectionAppend( final Object lhs, final Object rhs, final Class clazz, final CompareToBuilder builder, final boolean useTransients, final String[] excludeFields) { final Field[] fields = clazz.getDeclaredFields(); AccessibleObject.setAccessible(fields, true); for (int i = 0; i < fields.length && builder.comparison == 0; i++) { final Field f = fields[i]; if (false == ArrayUtil.contains(excludeFields, f.getName()) && (f.getName().indexOf('$') == -1) && (useTransients || !Modifier.isTransient(f.getModifiers())) && (!Modifier.isStatic(f.getModifiers()))) { try { builder.append(f.get(lhs), f.get(rhs)); } catch (final IllegalAccessException e) { // This can't happen. Would get a Security exception instead. // Throw a runtime exception in case the impossible happens. throw new InternalError("Unexpected IllegalAccessException"); } } } } //----------------------------------------------------------------------- /** *

Appends to the builder the compareTo(Object) * result of the superclass.

* * @param superCompareTo result of calling super.compareTo(Object) * @return this - used to chain append calls * @since 2.0 */ public CompareToBuilder appendSuper(final int superCompareTo) { if (comparison != 0) { return this; } comparison = superCompareTo; return this; } //----------------------------------------------------------------------- /** *

Appends to the builder the comparison of * two Objects.

* *
    *
  1. Check if lhs == rhs
  2. *
  3. Check if either lhs or rhs is null, * a null object is less than a non-null object
  4. *
  5. Check the object contents
  6. *
* *

lhs must either be an array or implement {@link Comparable}.

* * @param lhs left-hand object * @param rhs right-hand object * @return this - used to chain append calls * @throws ClassCastException if rhs is not assignment-compatible * with lhs */ public CompareToBuilder append(final Object lhs, final Object rhs) { return append(lhs, rhs, null); } /** *

Appends to the builder the comparison of * two Objects.

* *
    *
  1. Check if lhs == rhs
  2. *
  3. Check if either lhs or rhs is null, * a null object is less than a non-null object
  4. *
  5. Check the object contents
  6. *
* *

If lhs is an array, array comparison methods will be used. * Otherwise comparator will be used to compare the objects. * If comparator is null, lhs must * implement {@link Comparable} instead.

* * @param lhs left-hand object * @param rhs right-hand object * @param comparator Comparator used to compare the objects, * null means treat lhs as Comparable * @return this - used to chain append calls * @throws ClassCastException if rhs is not assignment-compatible * with lhs * @since 2.0 */ public CompareToBuilder append(final Object lhs, final Object rhs, final Comparator comparator) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == null) { comparison = -1; return this; } if (rhs == null) { comparison = +1; return this; } if (lhs.getClass().isArray()) { // switch on type of array, to dispatch to the correct handler // handles multi dimensional arrays // throws a ClassCastException if rhs is not the correct array type if (lhs instanceof long[]) { append((long[]) lhs, (long[]) rhs); } else if (lhs instanceof int[]) { append((int[]) lhs, (int[]) rhs); } else if (lhs instanceof short[]) { append((short[]) lhs, (short[]) rhs); } else if (lhs instanceof char[]) { append((char[]) lhs, (char[]) rhs); } else if (lhs instanceof byte[]) { append((byte[]) lhs, (byte[]) rhs); } else if (lhs instanceof double[]) { append((double[]) lhs, (double[]) rhs); } else if (lhs instanceof float[]) { append((float[]) lhs, (float[]) rhs); } else if (lhs instanceof boolean[]) { append((boolean[]) lhs, (boolean[]) rhs); } else { // not an array of primitives // throws a ClassCastException if rhs is not an array append((Object[]) lhs, (Object[]) rhs, comparator); } } else { // the simple case, not an array, just test the element if (comparator == null) { @SuppressWarnings("unchecked") // assume this can be done; if not throw CCE as per Javadoc final Comparable comparable = (Comparable) lhs; comparison = comparable.compareTo(rhs); } else { @SuppressWarnings("unchecked") // assume this can be done; if not throw CCE as per Javadoc final Comparator comparator2 = (Comparator) comparator; comparison = comparator2.compare(lhs, rhs); } } return this; } //------------------------------------------------------------------------- /** * Appends to the builder the comparison of * two longs. * * @param lhs left-hand value * @param rhs right-hand value * @return this - used to chain append calls */ public CompareToBuilder append(final long lhs, final long rhs) { if (comparison != 0) { return this; } comparison = (Long.compare(lhs, rhs)); return this; } /** * Appends to the builder the comparison of * two ints. * * @param lhs left-hand value * @param rhs right-hand value * @return this - used to chain append calls */ public CompareToBuilder append(final int lhs, final int rhs) { if (comparison != 0) { return this; } comparison = (Integer.compare(lhs, rhs)); return this; } /** * Appends to the builder the comparison of * two shorts. * * @param lhs left-hand value * @param rhs right-hand value * @return this - used to chain append calls */ public CompareToBuilder append(final short lhs, final short rhs) { if (comparison != 0) { return this; } comparison = (Short.compare(lhs, rhs)); return this; } /** * Appends to the builder the comparison of * two chars. * * @param lhs left-hand value * @param rhs right-hand value * @return this - used to chain append calls */ public CompareToBuilder append(final char lhs, final char rhs) { if (comparison != 0) { return this; } comparison = (Character.compare(lhs, rhs)); return this; } /** * Appends to the builder the comparison of * two bytes. * * @param lhs left-hand value * @param rhs right-hand value * @return this - used to chain append calls */ public CompareToBuilder append(final byte lhs, final byte rhs) { if (comparison != 0) { return this; } comparison = (Byte.compare(lhs, rhs)); return this; } /** *

Appends to the builder the comparison of * two doubles.

* *

This handles NaNs, Infinities, and -0.0.

* *

It is compatible with the hash code generated by * HashCodeBuilder.

* * @param lhs left-hand value * @param rhs right-hand value * @return this - used to chain append calls */ public CompareToBuilder append(final double lhs, final double rhs) { if (comparison != 0) { return this; } comparison = Double.compare(lhs, rhs); return this; } /** *

Appends to the builder the comparison of * two floats.

* *

This handles NaNs, Infinities, and -0.0.

* *

It is compatible with the hash code generated by * HashCodeBuilder.

* * @param lhs left-hand value * @param rhs right-hand value * @return this - used to chain append calls */ public CompareToBuilder append(final float lhs, final float rhs) { if (comparison != 0) { return this; } comparison = Float.compare(lhs, rhs); return this; } /** * Appends to the builder the comparison of * two booleanss. * * @param lhs left-hand value * @param rhs right-hand value * @return this - used to chain append calls */ public CompareToBuilder append(final boolean lhs, final boolean rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == false) { comparison = -1; } else { comparison = +1; } return this; } //----------------------------------------------------------------------- /** *

Appends to the builder the deep comparison of * two Object arrays.

* *
    *
  1. Check if arrays are the same using ==
  2. *
  3. Check if for null, null is less than non-null
  4. *
  5. Check array length, a short length array is less than a long length array
  6. *
  7. Check array contents element by element using {@link #append(Object, Object, Comparator)}
  8. *
* *

This method will also will be called for the top level of multi-dimensional, * ragged, and multi-typed arrays.

* * @param lhs left-hand array * @param rhs right-hand array * @return this - used to chain append calls * @throws ClassCastException if rhs is not assignment-compatible * with lhs */ public CompareToBuilder append(final Object[] lhs, final Object[] rhs) { return append(lhs, rhs, null); } /** *

Appends to the builder the deep comparison of * two Object arrays.

* *
    *
  1. Check if arrays are the same using ==
  2. *
  3. Check if for null, null is less than non-null
  4. *
  5. Check array length, a short length array is less than a long length array
  6. *
  7. Check array contents element by element using {@link #append(Object, Object, Comparator)}
  8. *
* *

This method will also will be called for the top level of multi-dimensional, * ragged, and multi-typed arrays.

* * @param lhs left-hand array * @param rhs right-hand array * @param comparator Comparator to use to compare the array elements, * null means to treat lhs elements as Comparable. * @return this - used to chain append calls * @throws ClassCastException if rhs is not assignment-compatible * with lhs * @since 2.0 */ public CompareToBuilder append(final Object[] lhs, final Object[] rhs, final Comparator comparator) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == null) { comparison = -1; return this; } if (rhs == null) { comparison = +1; return this; } if (lhs.length != rhs.length) { comparison = (lhs.length < rhs.length) ? -1 : +1; return this; } for (int i = 0; i < lhs.length && comparison == 0; i++) { append(lhs[i], rhs[i], comparator); } return this; } /** *

Appends to the builder the deep comparison of * two long arrays.

* *
    *
  1. Check if arrays are the same using ==
  2. *
  3. Check if for null, null is less than non-null
  4. *
  5. Check array length, a shorter length array is less than a longer length array
  6. *
  7. Check array contents element by element using {@link #append(long, long)}
  8. *
* * @param lhs left-hand array * @param rhs right-hand array * @return this - used to chain append calls */ public CompareToBuilder append(final long[] lhs, final long[] rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == null) { comparison = -1; return this; } if (rhs == null) { comparison = +1; return this; } if (lhs.length != rhs.length) { comparison = (lhs.length < rhs.length) ? -1 : +1; return this; } for (int i = 0; i < lhs.length && comparison == 0; i++) { append(lhs[i], rhs[i]); } return this; } /** *

Appends to the builder the deep comparison of * two int arrays.

* *
    *
  1. Check if arrays are the same using ==
  2. *
  3. Check if for null, null is less than non-null
  4. *
  5. Check array length, a shorter length array is less than a longer length array
  6. *
  7. Check array contents element by element using {@link #append(int, int)}
  8. *
* * @param lhs left-hand array * @param rhs right-hand array * @return this - used to chain append calls */ public CompareToBuilder append(final int[] lhs, final int[] rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == null) { comparison = -1; return this; } if (rhs == null) { comparison = +1; return this; } if (lhs.length != rhs.length) { comparison = (lhs.length < rhs.length) ? -1 : +1; return this; } for (int i = 0; i < lhs.length && comparison == 0; i++) { append(lhs[i], rhs[i]); } return this; } /** *

Appends to the builder the deep comparison of * two short arrays.

* *
    *
  1. Check if arrays are the same using ==
  2. *
  3. Check if for null, null is less than non-null
  4. *
  5. Check array length, a shorter length array is less than a longer length array
  6. *
  7. Check array contents element by element using {@link #append(short, short)}
  8. *
* * @param lhs left-hand array * @param rhs right-hand array * @return this - used to chain append calls */ public CompareToBuilder append(final short[] lhs, final short[] rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == null) { comparison = -1; return this; } if (rhs == null) { comparison = +1; return this; } if (lhs.length != rhs.length) { comparison = (lhs.length < rhs.length) ? -1 : +1; return this; } for (int i = 0; i < lhs.length && comparison == 0; i++) { append(lhs[i], rhs[i]); } return this; } /** *

Appends to the builder the deep comparison of * two char arrays.

* *
    *
  1. Check if arrays are the same using ==
  2. *
  3. Check if for null, null is less than non-null
  4. *
  5. Check array length, a shorter length array is less than a longer length array
  6. *
  7. Check array contents element by element using {@link #append(char, char)}
  8. *
* * @param lhs left-hand array * @param rhs right-hand array * @return this - used to chain append calls */ public CompareToBuilder append(final char[] lhs, final char[] rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == null) { comparison = -1; return this; } if (rhs == null) { comparison = +1; return this; } if (lhs.length != rhs.length) { comparison = (lhs.length < rhs.length) ? -1 : +1; return this; } for (int i = 0; i < lhs.length && comparison == 0; i++) { append(lhs[i], rhs[i]); } return this; } /** *

Appends to the builder the deep comparison of * two byte arrays.

* *
    *
  1. Check if arrays are the same using ==
  2. *
  3. Check if for null, null is less than non-null
  4. *
  5. Check array length, a shorter length array is less than a longer length array
  6. *
  7. Check array contents element by element using {@link #append(byte, byte)}
  8. *
* * @param lhs left-hand array * @param rhs right-hand array * @return this - used to chain append calls */ public CompareToBuilder append(final byte[] lhs, final byte[] rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == null) { comparison = -1; return this; } if (rhs == null) { comparison = +1; return this; } if (lhs.length != rhs.length) { comparison = (lhs.length < rhs.length) ? -1 : +1; return this; } for (int i = 0; i < lhs.length && comparison == 0; i++) { append(lhs[i], rhs[i]); } return this; } /** *

Appends to the builder the deep comparison of * two double arrays.

* *
    *
  1. Check if arrays are the same using ==
  2. *
  3. Check if for null, null is less than non-null
  4. *
  5. Check array length, a shorter length array is less than a longer length array
  6. *
  7. Check array contents element by element using {@link #append(double, double)}
  8. *
* * @param lhs left-hand array * @param rhs right-hand array * @return this - used to chain append calls */ public CompareToBuilder append(final double[] lhs, final double[] rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == null) { comparison = -1; return this; } if (rhs == null) { comparison = +1; return this; } if (lhs.length != rhs.length) { comparison = (lhs.length < rhs.length) ? -1 : +1; return this; } for (int i = 0; i < lhs.length && comparison == 0; i++) { append(lhs[i], rhs[i]); } return this; } /** *

Appends to the builder the deep comparison of * two float arrays.

* *
    *
  1. Check if arrays are the same using ==
  2. *
  3. Check if for null, null is less than non-null
  4. *
  5. Check array length, a shorter length array is less than a longer length array
  6. *
  7. Check array contents element by element using {@link #append(float, float)}
  8. *
* * @param lhs left-hand array * @param rhs right-hand array * @return this - used to chain append calls */ public CompareToBuilder append(final float[] lhs, final float[] rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == null) { comparison = -1; return this; } if (rhs == null) { comparison = +1; return this; } if (lhs.length != rhs.length) { comparison = (lhs.length < rhs.length) ? -1 : +1; return this; } for (int i = 0; i < lhs.length && comparison == 0; i++) { append(lhs[i], rhs[i]); } return this; } /** *

Appends to the builder the deep comparison of * two boolean arrays.

* *
    *
  1. Check if arrays are the same using ==
  2. *
  3. Check if for null, null is less than non-null
  4. *
  5. Check array length, a shorter length array is less than a longer length array
  6. *
  7. Check array contents element by element using {@link #append(boolean, boolean)}
  8. *
* * @param lhs left-hand array * @param rhs right-hand array * @return this - used to chain append calls */ public CompareToBuilder append(final boolean[] lhs, final boolean[] rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == null) { comparison = -1; return this; } if (rhs == null) { comparison = +1; return this; } if (lhs.length != rhs.length) { comparison = (lhs.length < rhs.length) ? -1 : +1; return this; } for (int i = 0; i < lhs.length && comparison == 0; i++) { append(lhs[i], rhs[i]); } return this; } //----------------------------------------------------------------------- /** * Returns a negative integer, a positive integer, or zero as * the builder has judged the "left-hand" side * as less than, greater than, or equal to the "right-hand" * side. * * @return final comparison result * @see #build() */ public int toComparison() { return comparison; } /** * Returns a negative Integer, a positive Integer, or zero as * the builder has judged the "left-hand" side * as less than, greater than, or equal to the "right-hand" * side. * * @return final comparison result as an Integer * @see #toComparison() * @since 3.0 */ @Override public Integer build() { return toComparison(); } }