利用反射的方式來獲取動態代理
反射是一種強大的工具,可以讓我們在運行時檢查和修改類的行為。以下是一些利用反射來獲取物件屬性和方法的例子。
獲取物件的屬性
我們可以使用反射來獲取物件中為 null 的屬性。以下是兩種實現方式:
方法一
public static String[] getNullPropertyNames(Object source) {
final BeanWrapper wrappedSource = new BeanWrapperImpl(source);
return Stream.of(wrappedSource.getPropertyDescriptors())
.map(FeatureDescriptor::getName)
.filter(propertyName -> wrappedSource.getPropertyValue(propertyName) == null)
.toArray(String[]::new);
}
方法二
public static String[] getNullPropertyNames(Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<>();
for (java.beans.PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null) emptyNames.add(pd.getName());
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
使用 Spring BeanUtils 來複製屬性並忽略 null 值
我們可以使用上面的方法來忽略 null 值,並使用 Spring 的 BeanUtils 來複製屬性:
public static void myCopyProperties(Object src, Object target) {
BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
}
這樣,我們就可以在複製屬性時忽略 null 值,確保目標物件不會被覆蓋為 null。