package com.shinedata.util.bean;
import com.shinedata.controller.TeacherInfoController;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @ClassName BeanUtils
* @Author yupanpan
* @Date 2019/9/10 14:09
*/
public class BeanUtils {
private static final Logger logger = LoggerFactory.getLogger(BeanUtils.class);
/**
* 拷贝实体,source,target不允许为空
* @param source
* @param target
*/
public static void copyProperties(Object source, Object target)throws Exception {
checkCopyProperties(source,target);
org.springframework.beans.BeanUtils.copyProperties(source, target);
}
/**
* 拷贝不为空的属性,source,target不允许为空,
* @param source
* @param target
*/
public static void copyNotNullProperties(Object source, Object target)throws Exception{
checkCopyProperties(source,target);
try {
Field[] fields = source.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
Object o = field.get(source);
if(o!=null&&!o.equals("")){
setFieldValueByFieldName(field.getName(),o,target);
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private static void checkCopyProperties(Object source, Object target)throws NullPointerException{
if(source==null||target==null){
logger.error("对象属性值复制失败");
throw new NullPointerException("source or target not null");
}
}
/**
* 拷贝实体集合,sourceList
*只支持自定义实体集合拷贝
*应用场景:DTO <=> DO 等
*/
public static void copyPropertiesList(List sourceList, List targetList, Class clazz) throws Exception {
if (CollectionUtils.isEmpty(sourceList)) {
throw new NullPointerException();
}
for (Object items : sourceList) {
Object target = clazz.newInstance();
org.springframework.beans.BeanUtils.copyProperties(items, target);
targetList.add(target);
}
}
/**
* Map --> Bean 2: 利用org.apache.commons.beanutils 工具类实现 Map --> Bean
* @param map
* @param obj
*/
public static void transMap2Bean2(Map<String, Object> map, Object obj) throws InvocationTargetException, IllegalAccessException {
if (map == null || obj == null) {
return;
}
org.apache.commons.beanutils.BeanUtils.populate(obj, map);
}
/**
* Map --> Bean 1: 利用Introspector,PropertyDescriptor实现 Map --> Bean
* @param map
* @param obj
*/
public static void transMap2Bean(Map<String, Object> map, Object obj) throws InvocationTargetException, IllegalAccessException, IntrospectionException {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (map.containsKey(key)) {
Object value = map.get(key);
// 得到property对应的setter方法
Method setter = property.getWriteMethod();
setter.invoke(obj, value);
}
}
}
/**
* Bean --> Map 1: 利用Introspector和PropertyDescriptor 将Bean --> Map
* @param obj
*/
public static Map<String, Object> transBean2Map(Object obj) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
if (obj == null) {
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
// 过滤class属性
if (!key.equals("class")) {
// 得到property对应的getter方法
Method getter = property.getReadMethod();
Object value = getter.invoke(obj);
map.put(key, value);
}
}
return map;
}
/**
* 反射根据属性名获取属性值
* @param fieldName 属性名
* @param object 实体类对象
* @return
*/
public static Object getFieldValueByFieldName(String fieldName, Object object) throws Exception{
checkfieldValueByFieldNameParam(fieldName, object);
try {
Field field = object.getClass().getDeclaredField(fieldName);
//设置对象的访问权限,保证对private的属性的访问
field.setAccessible(true);
return field.get(object);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 通过反射设置属性的值
* @param fieldName 属性名
* @param fieldValue 属性值
* @param object 实体类对象
* @param parameterTypes 设置属性值的类型
* @throws
*/
public static void setFieldValueByFieldName(String fieldName,Object fieldValue,Object object,Class<?>... parameterTypes)throws Exception {
checkfieldValueByFieldNameParam(fieldName, object);
if(fieldValue==null){
return;
}
try {
Field[] fields = object.getClass().getDeclaredFields();
for(int i=0;i<fields.length;i++){
Field field = fields[i];
//字段名称
String name = field.getName();
if(name.equals(fieldName)){
field.setAccessible(true);
field.set(object,fieldValue);
}
}
}catch (Exception e){
e.printStackTrace();
}
}
private static void checkfieldValueByFieldNameParam(String fieldName,Object object)throws NullPointerException{
if(StringUtils.isBlank(fieldName)){
logger.error("字段名不能为空");
throw new NullPointerException("reflex fieldName not null");
}
if(object==null){
logger.error("对象源不能为空");
throw new NullPointerException("reflex source not null");
}
}
/**
* 去除object所有String类型属性值的空格
* @author yupanpan
* @date 2019/9/25 10:04
* @param object
* @param b true-去除字符串所有空格 false-只去除头尾空格
* @return java.lang.Object
*/
public static Object formatBeanStringBlankSpace(Object object,Boolean b){
//获取该类中所有的域(属性)
Field[] fields = object.getClass().getDeclaredFields();
for(Field field : fields){
//对所有的属性判断是否为String类型
if(field.getType().equals(String.class)){
//将私有属性设置为可访问状态
field.setAccessible(true);
try {
Object o = field.get(object);
if(o!=null&&!o.equals("")){
String string = (String)o;
if(b){
string = string.replaceAll(" ","");
}else {
string=string.trim();
}
//相当于调用了set方法设置属性
field.set(object,string);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return object;
}
}
拿走可用,此文章BeanUtils工具类不间断持续更新其他好用的方法