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 * https://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) of the objects to diff are discovered using reflection and compared for differences.
33 * </p>
34 *
35 * <p>
36 * To use this class, write code as follows:
37 * </p>
38 *
39 * <pre>{@code
40 * public class Person implements Diffable<Person> {
41 * String name;
42 * int age;
43 * boolean smoker;
44 * ...
45 *
46 * public DiffResult<Person> diff(Person obj) {
47 * // No need for null check, as NullPointerException correct if obj is null
48 * return ReflectionDiffBuilder.<Person>builder()
49 * .setDiffBuilder(DiffBuilder.<Person>builder()
50 * .setLeft(this)
51 * .setRight(obj)
52 * .setStyle(ToStringStyle.SHORT_PREFIX_STYLE)
53 * .build())
54 * .setExcludeFieldNames("userName", "password")
55 * .build() // -> ReflectionDiffBuilder
56 * .build(); // -> DiffResult
57 * }
58 * }
59 * }</pre>
60 *
61 * <p>
62 * The {@link ToStringStyle} passed to the constructor is embedded in the returned {@link DiffResult} and influences the style of the
63 * {@code DiffResult.toString()} method. This style choice can be overridden by calling {@link DiffResult#toString(ToStringStyle)}.
64 * </p>
65 * <p>
66 * See {@link DiffBuilder} for a non-reflection based version of this class.
67 * </p>
68 *
69 * @param <T> type of the left and right object to diff.
70 * @see Diffable
71 * @see Diff
72 * @see DiffResult
73 * @see ToStringStyle
74 * @see DiffBuilder
75 * @since 3.6
76 */
77 public class ReflectionDiffBuilder<T> implements Builder<DiffResult<T>> {
78
79 /**
80 * Constructs a new instance.
81 *
82 * @param <T> type of the left and right object.
83 * @since 3.15.0
84 */
85 public static final class Builder<T> {
86
87 private String[] excludeFieldNames = ArrayUtils.EMPTY_STRING_ARRAY;
88 private DiffBuilder<T> diffBuilder;
89
90 /**
91 * Constructs a new instance.
92 */
93 public Builder() {
94 // empty
95 }
96
97 /**
98 * Builds a new configured {@link ReflectionDiffBuilder}.
99 *
100 * @return a new configured {@link ReflectionDiffBuilder}.
101 */
102 public ReflectionDiffBuilder<T> build() {
103 return new ReflectionDiffBuilder<>(diffBuilder, excludeFieldNames);
104 }
105
106 /**
107 * Sets the DiffBuilder.
108 *
109 * @param diffBuilder the DiffBuilder.
110 * @return {@code this} instance.
111 */
112 public Builder<T> setDiffBuilder(final DiffBuilder<T> diffBuilder) {
113 this.diffBuilder = diffBuilder;
114 return this;
115 }
116
117 /**
118 * Sets field names to exclude from output. Intended for fields like {@code "password"} or {@code "lastModificationDate"}.
119 *
120 * @param excludeFieldNames field names to exclude.
121 * @return {@code this} instance.
122 */
123 public Builder<T> setExcludeFieldNames(final String... excludeFieldNames) {
124 this.excludeFieldNames = toExcludeFieldNames(excludeFieldNames);
125 return this;
126 }
127
128 }
129
130 /**
131 * Constructs a new {@link Builder}.
132 *
133 * @param <T> type of the left and right object.
134 * @return a new {@link Builder}.
135 * @since 3.15.0
136 */
137 public static <T> Builder<T> builder() {
138 return new Builder<>();
139 }
140
141 private static String[] toExcludeFieldNames(final String[] excludeFieldNames) {
142 if (excludeFieldNames == null) {
143 return ArrayUtils.EMPTY_STRING_ARRAY;
144 }
145 // clone and remove nulls
146 return ArraySorter.sort(ReflectionToStringBuilder.toNoNullStringArray(excludeFieldNames));
147 }
148
149 private final DiffBuilder<T> diffBuilder;
150
151 /**
152 * Field names to exclude from output. Intended for fields like {@code "password"} or {@code "lastModificationDate"}.
153 */
154 private String[] excludeFieldNames;
155
156 private ReflectionDiffBuilder(final DiffBuilder<T> diffBuilder, final String[] excludeFieldNames) {
157 this.diffBuilder = diffBuilder;
158 this.excludeFieldNames = excludeFieldNames;
159 }
160
161 /**
162 * Constructs a builder for the specified objects with the specified style.
163 *
164 * <p>
165 * If {@code left == right} or {@code left.equals(right)} then the builder will not evaluate any calls to {@code append(...)} and will return an empty
166 * {@link DiffResult} when {@link #build()} is executed.
167 * </p>
168 *
169 * @param left {@code this} object.
170 * @param right the object to diff against.
171 * @param style the style will use when outputting the objects, {@code null} uses the default
172 * @throws IllegalArgumentException if {@code left} or {@code right} is {@code null}.
173 * @deprecated Use {@link Builder}.
174 */
175 @Deprecated
176 public ReflectionDiffBuilder(final T left, final T right, final ToStringStyle style) {
177 this(DiffBuilder.<T>builder().setLeft(left).setRight(right).setStyle(style).build(), null);
178 }
179
180 private boolean accept(final Field field) {
181 if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
182 return false;
183 }
184 if (Modifier.isTransient(field.getModifiers())) {
185 return false;
186 }
187 if (Modifier.isStatic(field.getModifiers())) {
188 return false;
189 }
190 if (this.excludeFieldNames != null && Arrays.binarySearch(this.excludeFieldNames, field.getName()) >= 0) {
191 // Reject fields from the getExcludeFieldNames list.
192 return false;
193 }
194 return !field.isAnnotationPresent(DiffExclude.class);
195 }
196
197 /**
198 * Appends fields using reflection.
199 *
200 * @throws SecurityException if an underlying accessible object's method denies the request.
201 * @see SecurityManager#checkPermission
202 */
203 private void appendFields(final Class<?> clazz) {
204 for (final Field field : FieldUtils.getAllFields(clazz)) {
205 if (accept(field)) {
206 try {
207 diffBuilder.append(field.getName(), readField(field, getLeft()), readField(field, getRight()));
208 } catch (final IllegalAccessException e) {
209 // this can't happen. Would get a Security exception instead
210 // throw a runtime exception in case the impossible happens.
211 throw new IllegalArgumentException("Unexpected IllegalAccessException: " + e.getMessage(), e);
212 }
213 }
214 }
215 }
216
217 /**
218 * {@inheritDoc}
219 *
220 * @throws SecurityException if an underlying accessible object's method denies the request.
221 * @see SecurityManager#checkPermission
222 */
223 @Override
224 public DiffResult<T> build() {
225 if (getLeft().equals(getRight())) {
226 return diffBuilder.build();
227 }
228 appendFields(getLeft().getClass());
229 return diffBuilder.build();
230 }
231
232 /**
233 * Gets the field names that should be excluded from the diff.
234 *
235 * @return the excludeFieldNames.
236 * @since 3.13.0
237 */
238 public String[] getExcludeFieldNames() {
239 return this.excludeFieldNames.clone();
240 }
241
242 private T getLeft() {
243 return diffBuilder.getLeft();
244 }
245
246 private T getRight() {
247 return diffBuilder.getRight();
248 }
249
250 /**
251 * Reads a {@link Field}, forcing access if needed.
252 *
253 * @param field
254 * the field to use
255 * @param target
256 * the object to call on, may be {@code null} for {@code static} fields
257 * @return the field value
258 * @throws NullPointerException
259 * if the field is {@code null}
260 * @throws IllegalAccessException
261 * if the field is not made accessible
262 * @throws SecurityException if an underlying accessible object's method denies the request.
263 * @see SecurityManager#checkPermission
264 */
265 private Object readField(final Field field, final Object target) throws IllegalAccessException {
266 return FieldUtils.readField(field, target, true);
267 }
268
269 /**
270 * Sets the field names to exclude.
271 *
272 * @param excludeFieldNames The field names to exclude from the diff or {@code null}.
273 * @return {@code this}
274 * @since 3.13.0
275 * @deprecated Use {@link Builder#setExcludeFieldNames(String[])}.
276 */
277 @Deprecated
278 public ReflectionDiffBuilder<T> setExcludeFieldNames(final String... excludeFieldNames) {
279 this.excludeFieldNames = toExcludeFieldNames(excludeFieldNames);
280 return this;
281 }
282
283 }