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 * https://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) of the objects to diff are discovered using reflection and compared for differences. 033 * </p> 034 * 035 * <p> 036 * To use this class, write code as follows: 037 * </p> 038 * 039 * <pre>{@code 040 * public class Person implements Diffable<Person> { 041 * String name; 042 * int age; 043 * boolean smoker; 044 * ... 045 * 046 * public DiffResult<Person> diff(Person obj) { 047 * // No need for null check, as NullPointerException correct if obj is null 048 * return ReflectionDiffBuilder.<Person>builder() 049 * .setDiffBuilder(DiffBuilder.<Person>builder() 050 * .setLeft(this) 051 * .setRight(obj) 052 * .setStyle(ToStringStyle.SHORT_PREFIX_STYLE) 053 * .build()) 054 * .setExcludeFieldNames("userName", "password") 055 * .build() // -> ReflectionDiffBuilder 056 * .build(); // -> DiffResult 057 * } 058 * } 059 * }</pre> 060 * 061 * <p> 062 * The {@link ToStringStyle} passed to the constructor is embedded in the returned {@link DiffResult} and influences the style of the 063 * {@code DiffResult.toString()} method. This style choice can be overridden by calling {@link DiffResult#toString(ToStringStyle)}. 064 * </p> 065 * <p> 066 * See {@link DiffBuilder} for a non-reflection based version of this class. 067 * </p> 068 * 069 * @param <T> type of the left and right object to diff. 070 * @see Diffable 071 * @see Diff 072 * @see DiffResult 073 * @see ToStringStyle 074 * @see DiffBuilder 075 * @since 3.6 076 */ 077public class ReflectionDiffBuilder<T> implements Builder<DiffResult<T>> { 078 079 /** 080 * Constructs a new instance. 081 * 082 * @param <T> type of the left and right object. 083 * @since 3.15.0 084 */ 085 public static final class Builder<T> { 086 087 private String[] excludeFieldNames = ArrayUtils.EMPTY_STRING_ARRAY; 088 private DiffBuilder<T> diffBuilder; 089 090 /** 091 * Constructs a new instance. 092 */ 093 public Builder() { 094 // empty 095 } 096 097 /** 098 * Builds a new configured {@link ReflectionDiffBuilder}. 099 * 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}