1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.lang3.builder;
18
19 import java.lang.reflect.Field;
20 import java.lang.reflect.Modifier;
21 import java.util.Arrays;
22
23 import org.apache.commons.lang3.ArraySorter;
24 import org.apache.commons.lang3.ArrayUtils;
25 import org.apache.commons.lang3.ClassUtils;
26 import org.apache.commons.lang3.reflect.FieldUtils;
27
28 /**
29 * Assists in implementing {@link Diffable#diff(Object)} methods.
30 *
31 * <p>
32 * All non-static, non-transient fields (including inherited fields)
33 * of the objects to diff are discovered using reflection and compared
34 * for differences.
35 * </p>
36 *
37 * <p>
38 * To use this class, write code as follows:
39 * </p>
40 *
41 * <pre>
42 * public class Person implements Diffable<Person> {
43 * String name;
44 * int age;
45 * boolean smoker;
46 * ...
47 *
48 * public DiffResult diff(Person obj) {
49 * // No need for null check, as NullPointerException correct if obj is null
50 * return new ReflectionDiffBuilder(this, obj, ToStringStyle.SHORT_PREFIX_STYLE)
51 * .build();
52 * }
53 * }
54 * </pre>
55 *
56 * <p>
57 * The {@link ToStringStyle} passed to the constructor is embedded in the
58 * returned {@link DiffResult} and influences the style of the
59 * {@code DiffResult.toString()} method. This style choice can be overridden by
60 * calling {@link DiffResult#toString(ToStringStyle)}.
61 * </p>
62 * <p>
63 * See {@link DiffBuilder} for a non-reflection based version of this class.
64 * </p>
65 * @param <T>
66 * type of the left and right object to diff.
67 * @see Diffable
68 * @see Diff
69 * @see DiffResult
70 * @see ToStringStyle
71 * @see DiffBuilder
72 * @since 3.6
73 */
74 public class ReflectionDiffBuilder<T> implements Builder<DiffResult<T>> {
75
76 private final T left;
77 private final T right;
78 private final DiffBuilder<T> diffBuilder;
79
80 /**
81 * Field names to exclude from output. Intended for fields like {@code "password"} or {@code "lastModificationDate"}.
82 *
83 * @since 3.13.0
84 */
85 private String[] excludeFieldNames;
86
87 /**
88 * Constructs a builder for the specified objects with the specified style.
89 *
90 * <p>
91 * If {@code lhs == rhs} or {@code lhs.equals(rhs)} then the builder will
92 * not evaluate any calls to {@code append(...)} and will return an empty
93 * {@link DiffResult} when {@link #build()} is executed.
94 * </p>
95 * @param lhs
96 * {@code this} object
97 * @param rhs
98 * the object to diff against
99 * @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 private boolean accept(final Field field) {
112 if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
113 return false;
114 }
115 if (Modifier.isTransient(field.getModifiers())) {
116 return false;
117 }
118 if (Modifier.isStatic(field.getModifiers())) {
119 return false;
120 }
121 if (this.excludeFieldNames != null
122 && Arrays.binarySearch(this.excludeFieldNames, field.getName()) >= 0) {
123 // Reject fields from the getExcludeFieldNames list.
124 return false;
125 }
126 return !field.isAnnotationPresent(DiffExclude.class);
127 }
128
129
130 private void appendFields(final Class<?> clazz) {
131 for (final Field field : FieldUtils.getAllFields(clazz)) {
132 if (accept(field)) {
133 try {
134 diffBuilder.append(field.getName(), FieldUtils.readField(field, left, true), FieldUtils.readField(field, right, true));
135 } catch (final IllegalAccessException e) {
136 // this can't happen. Would get a Security exception instead
137 // throw a runtime exception in case the impossible happens.
138 throw new IllegalArgumentException("Unexpected IllegalAccessException: " + e.getMessage(), e);
139 }
140 }
141 }
142 }
143
144 @Override
145 public DiffResult<T> build() {
146 if (left.equals(right)) {
147 return diffBuilder.build();
148 }
149
150 appendFields(left.getClass());
151 return diffBuilder.build();
152 }
153
154 /**
155 * Gets the field names that should be excluded from the diff.
156 *
157 * @return Returns the excludeFieldNames.
158 * @since 3.13.0
159 */
160 public String[] getExcludeFieldNames() {
161 return this.excludeFieldNames.clone();
162 }
163
164 /**
165 * Sets the field names to exclude.
166 *
167 * @param excludeFieldNamesParam
168 * The field names to exclude from the diff or {@code null}.
169 * @return {@code this}
170 * @since 3.13.0
171 */
172 public ReflectionDiffBuilder<T> setExcludeFieldNames(final String... excludeFieldNamesParam) {
173 if (excludeFieldNamesParam == null) {
174 this.excludeFieldNames = ArrayUtils.EMPTY_STRING_ARRAY;
175 } else {
176 // clone and remove nulls
177 this.excludeFieldNames = ArraySorter.sort(ReflectionToStringBuilder.toNoNullStringArray(excludeFieldNamesParam));
178 }
179 return this;
180 }
181
182 }