    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.lang3.builder;
    018
    019import java.lang.reflect.Field;
    020import java.lang.reflect.Modifier;
    021import java.util.Arrays;
    022
    023import org.apache.commons.lang3.ArraySorter;
    024import org.apache.commons.lang3.ArrayUtils;
    025import org.apache.commons.lang3.ClassUtils;
    026import org.apache.commons.lang3.reflect.FieldUtils;
    027
    028/**
    029 * Assists in implementing {@link Diffable#diff(Object)} methods.
    030 *
    031 * <p>
    032 * All non-static, non-transient fields (including inherited fields)
    033 * of the objects to diff are discovered using reflection and compared
    034 * for differences.
    035 * </p>
    036 *
    037 * <p>
    038 * To use this class, write code as follows:
    039 * </p>
    040 *
    041 * <pre>
    042 * public class Person implements Diffable&lt;Person&gt; {
    043 *   String name;
    044 *   int age;
    045 *   boolean smoker;
    046 *   ...
    047 *
    048 *   public DiffResult diff(Person obj) {
    049 *     // No need for null check, as NullPointerException correct if obj is null
    050 *     return new ReflectionDiffBuilder(this, obj, ToStringStyle.SHORT_PREFIX_STYLE)
    051 *       .build();
    052 *   }
    053 * }
    054 * </pre>
    055 *
    056 * <p>
    057 * The {@link ToStringStyle} passed to the constructor is embedded in the
    058 * returned {@link DiffResult} and influences the style of the
    059 * {@code DiffResult.toString()} method. This style choice can be overridden by
    060 * calling {@link DiffResult#toString(ToStringStyle)}.
    061 * </p>
    062 * <p>
    063 * See {@link DiffBuilder} for a non-reflection based version of this class.
    064 * </p>
    065 * @param <T>
    066 *            type of the left and right object to diff.
    067 * @see Diffable
    068 * @see Diff
    069 * @see DiffResult
    070 * @see ToStringStyle
    071 * @see DiffBuilder
    072 * @since 3.6
    073 */
    074public class ReflectionDiffBuilder<T> implements Builder<DiffResult<T>> {
    075
    076    private final T left;
    077    private final T right;
    078    private final DiffBuilder<T> diffBuilder;
    079
    080    /**
    081     * Field names to exclude from output. Intended for fields like {@code "password"} or {@code "lastModificationDate"}.
    082     *
    083     * @since 3.13.0
    084     */
    085    private String[] excludeFieldNames;
    086
    087    /**
    088     * Constructs a builder for the specified objects with the specified style.
    089     *
    090     * <p>
    091     * If {@code lhs == rhs} or {@code lhs.equals(rhs)} then the builder will
    092     * not evaluate any calls to {@code append(...)} and will return an empty
    093     * {@link DiffResult} when {@link #build()} is executed.
    094     * </p>
    095     * @param lhs
    096     *            {@code this} object
    097     * @param rhs
    098     *            the object to diff against
    099     * @param style
    100     *            the style will use when outputting the objects, {@code null}
    101     *            uses the default
    102     * @throws IllegalArgumentException
    103     *             if {@code lhs} or {@code rhs} is {@code null}
    104     */
    105    public ReflectionDiffBuilder(final T lhs, final T rhs, final ToStringStyle style) {
    106        this.left = lhs;
    107        this.right = rhs;
    108        this.diffBuilder = new DiffBuilder<>(lhs, rhs, style);
    109    }
    110
    111    /**
    112     * Gets the field names that should be excluded from the diff.
    113     *
    114     * @return Returns the excludeFieldNames.
    115     * @since 3.13.0
    116     */
    117    public String[] getExcludeFieldNames() {
    118        return this.excludeFieldNames.clone();
    119    }
    120
    121
    122    /**
    123     * Sets the field names to exclude.
    124     *
    125     * @param excludeFieldNamesParam
    126     *            The field names to exclude from the diff or {@code null}.
    127     * @return {@code this}
    128     * @since 3.13.0
    129     */
    130    public ReflectionDiffBuilder<T> setExcludeFieldNames(final String... excludeFieldNamesParam) {
    131        if (excludeFieldNamesParam == null) {
    132            this.excludeFieldNames = ArrayUtils.EMPTY_STRING_ARRAY;
    133        } else {
    134            // clone and remove nulls
    135            this.excludeFieldNames = ArraySorter.sort(ReflectionToStringBuilder.toNoNullStringArray(excludeFieldNamesParam));
    136        }
    137        return this;
    138    }
    139
    140    @Override
    141    public DiffResult<T> build() {
    142        if (left.equals(right)) {
    143            return diffBuilder.build();
    144        }
    145
    146        appendFields(left.getClass());
    147        return diffBuilder.build();
    148    }
    149
    150    private void appendFields(final Class<?> clazz) {
    151        for (final Field field : FieldUtils.getAllFields(clazz)) {
    152            if (accept(field)) {
    153                try {
    154                    diffBuilder.append(field.getName(), FieldUtils.readField(field, left, true), FieldUtils.readField(field, right, true));
    155                } catch (final IllegalAccessException e) {
    156                    // this can't happen. Would get a Security exception instead
    157                    // throw a runtime exception in case the impossible happens.
    158                    throw new IllegalArgumentException("Unexpected IllegalAccessException: " + e.getMessage(), e);
    159                }
    160            }
    161        }
    162    }
    163
    164    private boolean accept(final Field field) {
    165        if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
    166            return false;
    167        }
    168        if (Modifier.isTransient(field.getModifiers())) {
    169            return false;
    170        }
    171        if (Modifier.isStatic(field.getModifiers())) {
    172            return false;
    173        }
    174        if (this.excludeFieldNames != null
    175                && Arrays.binarySearch(this.excludeFieldNames, field.getName()) >= 0) {
    176            // Reject fields from the getExcludeFieldNames list.
    177            return false;
    178        }
    179        return !field.isAnnotationPresent(DiffExclude.class);
    180    }
    181
    182}