Last active
December 28, 2020 06:22
-
-
Save junxy/da05a2b11177c1a92ac430892909bbec to your computer and use it in GitHub Desktop.
Bean属性复制 忽略空值/空白字符
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test; | |
import org.apache.commons.lang.StringUtils; | |
import org.springframework.beans.BeanUtils; | |
import org.springframework.beans.BeanWrapper; | |
import org.springframework.beans.BeanWrapperImpl; | |
import java.beans.PropertyDescriptor; | |
import java.util.HashSet; | |
import java.util.Set; | |
public class BeanUtils2 { | |
public static void copyProperties(Object source, Object target) { | |
BeanUtils.copyProperties(source, target, getNullOrEmptyPropertyNames(source)); | |
} | |
public static String[] getNullOrEmptyPropertyNames(Object source) { | |
final BeanWrapper src = new BeanWrapperImpl(source); | |
PropertyDescriptor[] pds = src.getPropertyDescriptors(); | |
Set<String> emptyNames = new HashSet<>(); | |
for (PropertyDescriptor pd : pds) { | |
Object srcValue = src.getPropertyValue(pd.getName()); | |
// 此处判断可根据需求修改 | |
if (srcValue == null || StringUtils.isBlank(srcValue + "")) { | |
emptyNames.add(pd.getName()); | |
} | |
} | |
String[] result = new String[emptyNames.size()]; | |
return emptyNames.toArray(result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ref: http://blog.wya1.com/article/Internet/details/3061