View Javadoc
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  import java.util.Objects;
23  
24  import org.apache.commons.lang3.ArraySorter;
25  import org.apache.commons.lang3.ArrayUtils;
26  import org.apache.commons.lang3.ClassUtils;
27  import org.apache.commons.lang3.reflect.FieldUtils;
28  
29  /**
30   * Assists in implementing {@link Diffable#diff(Object)} methods.
31   *
32   * <p>
33   * All non-static, non-transient fields (including inherited fields) of the objects to diff are discovered using reflection and compared for differences.
34   * </p>
35   *
36   * <p>
37   * To use this class, write code as follows:
38   * </p>
39   *
40   * <pre>{@code
41   * public class Person implements Diffable<Person> {
42   *   String name;
43   *   int age;
44   *   boolean smoker;
45   *   ...
46   *
47   *   public DiffResult<Person> diff(Person obj) {
48   *     // No need for null check, as NullPointerException correct if obj is null
49   *     return ReflectionDiffBuilder.<Person>builder()
50   *       .setDiffBuilder(DiffBuilder.<Person>builder()
51   *           .setLeft(this)
52   *           .setRight(obj)
53   *           .setStyle(ToStringStyle.SHORT_PREFIX_STYLE)
54   *           .build())
55   *       .setExcludeFieldNames("userName", "password")
56   *       .build()  // -> ReflectionDiffBuilder
57   *       .build(); // -> DiffResult
58   *   }
59   * }
60   * }</pre>
61   *
62   * <p>
63   * The {@link ToStringStyle} passed to the constructor is embedded in the returned {@link DiffResult} and influences the style of the
64   * {@code DiffResult.toString()} method. This style choice can be overridden by calling {@link DiffResult#toString(ToStringStyle)}.
65   * </p>
66   * <p>
67   * See {@link DiffBuilder} for a non-reflection based version of this class.
68   * </p>
69   *
70   * @param <T> type of the left and right object to diff.
71   * @see Diffable
72   * @see Diff
73   * @see DiffResult
74   * @see ToStringStyle
75   * @see DiffBuilder
76   * @since 3.6
77   */
78  public class ReflectionDiffBuilder<T> implements Builder<DiffResult<T>> {
79  
80      /**
81       * Constructs a new instance.
82       *
83       * @param <T> type of the left and right object.
84       * @since 3.15.0
85       */
86      public static final class Builder<T> {
87  
88          private String[] excludeFieldNames = ArrayUtils.EMPTY_STRING_ARRAY;
89          private DiffBuilder<T> diffBuilder;
90  
91          /**
92           * Constructs a new instance.
93           */
94          public Builder() {
95              // empty
96          }
97  
98          /**
99           * Builds a new configured {@link ReflectionDiffBuilder}.
100          *
101          * @return a new configured {@link ReflectionDiffBuilder}.
102          */
103         public ReflectionDiffBuilder<T> build() {
104             return new ReflectionDiffBuilder<>(diffBuilder, excludeFieldNames);
105         }
106 
107         /**
108          * Sets the DiffBuilder.
109          *
110          * @param diffBuilder the DiffBuilder.
111          * @return {@code this} instance.
112          */
113         public Builder<T> setDiffBuilder(final DiffBuilder<T> diffBuilder) {
114             this.diffBuilder = diffBuilder;
115             return this;
116         }
117 
118         /**
119          * Sets field names to exclude from output. Intended for fields like {@code "password"} or {@code "lastModificationDate"}.
120          *
121          * @param excludeFieldNames field names to exclude.
122          * @return {@code this} instance.
123          */
124         public Builder<T> setExcludeFieldNames(final String... excludeFieldNames) {
125             this.excludeFieldNames = toExcludeFieldNames(excludeFieldNames);
126             return this;
127         }
128 
129     }
130 
131     /**
132      * Constructs a new {@link Builder}.
133      *
134      * @param <T> type of the left and right object.
135      * @return a new {@link Builder}.
136      * @since 3.15.0
137      */
138     public static <T> Builder<T> builder() {
139         return new Builder<>();
140     }
141 
142     private static String[] toExcludeFieldNames(final String[] excludeFieldNames) {
143         if (excludeFieldNames == null) {
144             return ArrayUtils.EMPTY_STRING_ARRAY;
145         }
146         // clone and remove nulls
147         return ArraySorter.sort(ReflectionToStringBuilder.toNoNullStringArray(excludeFieldNames));
148     }
149 
150     private final DiffBuilder<T> diffBuilder;
151 
152     /**
153      * Field names to exclude from output. Intended for fields like {@code "password"} or {@code "lastModificationDate"}.
154      */
155     private String[] excludeFieldNames;
156 
157     /**
158      * Constructs a new instance.
159      *
160      * @param diffBuilder a non-null DiffBuilder.
161      * @param excludeFieldNames a non-null String array.
162      * @throw NullPointerException Thrown on null input.
163      */
164     private ReflectionDiffBuilder(final DiffBuilder<T> diffBuilder, final String[] excludeFieldNames) {
165         this.diffBuilder = Objects.requireNonNull(diffBuilder, "diffBuilder");
166         this.excludeFieldNames = Objects.requireNonNull(excludeFieldNames, "excludeFieldNames");
167     }
168 
169     /**
170      * Constructs a builder for the specified objects with the specified style.
171      *
172      * <p>
173      * 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
174      * {@link DiffResult} when {@link #build()} is executed.
175      * </p>
176      *
177      * @param left  {@code this} object.
178      * @param right the object to diff against.
179      * @param style the style will use when outputting the objects, {@code null} uses the default
180      * @throws IllegalArgumentException if {@code left} or {@code right} is {@code null}.
181      * @deprecated Use {@link Builder}.
182      */
183     @Deprecated
184     public ReflectionDiffBuilder(final T left, final T right, final ToStringStyle style) {
185         this(DiffBuilder.<T>builder().setLeft(left).setRight(right).setStyle(style).build(), ArrayUtils.EMPTY_STRING_ARRAY);
186     }
187 
188     private boolean accept(final Field field) {
189         if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1 || Modifier.isTransient(field.getModifiers())
190                 || Modifier.isStatic(field.getModifiers()) || Arrays.binarySearch(excludeFieldNames, field.getName()) >= 0) {
191             // Rejected.
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 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  the field to use.
254      * @param target the object to call on, may be {@code null} for {@code static} fields.
255      * @return the field value.
256      * @throws NullPointerException   if the field is {@code null}.
257      * @throws IllegalAccessException if the field is not made accessible.
258      * @throws SecurityException      if an underlying accessible object's method denies the request.
259      * @see SecurityManager#checkPermission
260      */
261     private Object readField(final Field field, final Object target) throws IllegalAccessException {
262         return FieldUtils.readField(field, target, true);
263     }
264 
265     /**
266      * Sets the field names to exclude.
267      *
268      * @param excludeFieldNames The field names to exclude from the diff or {@code null}.
269      * @return {@code this} instance.
270      * @since 3.13.0
271      * @deprecated Use {@link Builder#setExcludeFieldNames(String[])}.
272      */
273     @Deprecated
274     public ReflectionDiffBuilder<T> setExcludeFieldNames(final String... excludeFieldNames) {
275         this.excludeFieldNames = toExcludeFieldNames(excludeFieldNames);
276         return this;
277     }
278 
279 }