反射获取属性名和获取属性值

package com.hisense.smartroad.common.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.ss.formula.functions.T;

import com.hisense.smartroad.saf.securitymanagement.entity.Bdf2DeptSaf;
import com.hisense.smartroad.saf.securitymanagement.entity.SafTBaseStaff;

/**
 * 反射工具类
 * 
 * @author xl
 * 
 */
public class ReflectUtils {
	private T original; // 原数据
	private T current; // 当前数据
	private static final String YYYY_MM_DD = "yyyy-MM-dd";
	private static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd hh:mm:ss";

	private ReflectUtils() {}

	/**
	 * 反射设置属性和值,用于导出 partten : 时间格式化
	 */
	public static Map<String, Object> setReflectValue(Object obj, String partten) {
		Map<String, Object> map = new HashMap<>();
		try {
			Class clazz = obj.getClass();
			Field[] fs = clazz.getDeclaredFields();
			for (Field field : fs) {
				field.setAccessible(true);// 设置能够访问私有方法
				if ("serialVersionUID".equals(field.getName())) {
					continue;
				}
				if (field.getType().equals("Date")) {
					String date = DateFormatUtils.format((Date) field.get(obj),YYYY_MM_DD);
					if (!StringUtils.isEmpty(partten)) {
						date = DateFormatUtils.format((Date) field.get(obj),partten);
					}
					map.put(field.getName(), date);
					continue;
				}
				System.out.println(field.getName() + ":::::::::::::::::::::" + field.get(obj));
				map.put(field.getName(),field.get(obj) == null ? "" : field.get(obj));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return map;
	}
	
	/**
	 * 反射设置属性和值,用于导出 partten : 时间格式化
	 */
	public static MapEx<String, Object> setReflectValueMapEx(Object obj, String partten) {
		MapEx<String, Object> map = new MapEx<>();
		try {
			Class clazz = obj.getClass();
			Field[] fs = clazz.getDeclaredFields();
			for (Field field : fs) {
				System.out.println(field.getName());
				field.setAccessible(true);// 设置能够访问私有方法
				if ("serialVersionUID".equals(field.getName())) {
					continue;
				}

				if (field.getType().getName().equals("com.hisense.smartroad.saf.securitymanagement.entity.Bdf2DeptSaf")) {
					Bdf2DeptSaf dept = (Bdf2DeptSaf)field.get(obj);
					map.put(field.getName(),field.get(obj) == null ? "" : dept.getDesc());
					continue;
				}
				if (field.getType().getName().equals("com.hisense.smartroad.saf.securitymanagement.entity.SafTBaseStaff")) {
					SafTBaseStaff staff = (SafTBaseStaff)field.get(obj);
					map.put(field.getName(),field.get(obj) == null ? "" : staff.getStaffName());
					continue;
				}
				if (field.getType().getName().equals("java.util.Date")) {
					String date = DateFormatUtils.format((Date) field.get(obj),YYYY_MM_DD);
					if (!StringUtils.isEmpty(partten)) {
						date = DateFormatUtils.format((Date) field.get(obj),partten);
					}
					map.put(field.getName(), date);
					continue;
				}
				System.out.println("反射实体:" + field.getName() + "-----------------------------" + field.get(obj));
				map.put(field.getName(),field.get(obj) == null ? "" : field.get(obj));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return map;
	}
	
	/**
	 * 反射获取俩对象同一属性的新旧值
	 * oldObj:就对象 
	 * currentObj:当前对象
	 * dealField:需要处理的列
	 */
	public static List<Map<String,Object>> getNewAndOldValue(Object oldObj, Object currentObj,Map<String,Object> dealField){
		List<Map<String,Object>> list = new ArrayList<>();
		try {
			Class<? extends Object> clazz = oldObj.getClass();
		    Field[] fields = clazz.getDeclaredFields();
		    for (Field field : fields) {
		    	if (field.getName().equals("serialVersionUID")) {
					continue;
				}		    	
				PropertyDescriptor pd = new PropertyDescriptor(field.getName(),clazz);
				Method getMethod = pd.getReadMethod();
				String type = field.getType().getName();
				if ("java.util.Set".equals(type)) {
					continue;
				}

				Object old = getMethod.invoke(oldObj);
				Object current = getMethod.invoke(currentObj);
				if (dealField != null) {
					if (dealField.get("compareField").equals(field.getName())) {
						Map<String,Object> map = new HashMap<>();
						map.put("field", field.getName());
						map.put(dealField.get("needField").toString(),currentObj);
						map.put("old", old);
						map.put("current", current);
						list.add(map);
						continue;
					} 
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 反射对比数据值是否发生改变
	 */
	public String contrastObj(Class<T> cls) {
		StringBuilder sb = new StringBuilder();
		try {
			Field[] fields = cls.getDeclaredFields();
			for (Field field : fields) {
				PropertyDescriptor pd = new PropertyDescriptor(field.getName(),cls);
				Method getMethod = pd.getReadMethod();
				String type = field.getType().getName();
				if (!"java.util.Set".equals(type)) {
					Object o1 = getMethod.invoke(this.original);
					Object o2 = getMethod.invoke(this.current);
					if (null != o2) {
						String s1 = o1 == null ? "" : o1.toString();
						String s2 = o2 == null ? "" : o2.toString();
						if (!s1.equals(s2)) {
							System.out.println("不一样的属性:" + field.getName() + " 属性值:[" + s1 + "," + s2 + "]");
							sb.append(field.getName() + ":" + "[" + s1 + "," + s2 + "];");
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	/**
     * 复制对象属性(对象类型必须相同)
     * @param orig 资源对象
     * @param dest 目标对象
     * @param clazz 源对象类
     * @param ignoreNull 是否忽略空(true:忽略,false:不忽略)
     * @param ignoreExist  是否只复制dest值为空的数据  true 是,false 否
     */
    public static <T> T copyProperties(T orig, T dest, Class<?> clazz, boolean ignoreNull,boolean ignoreExist) {
        if (orig == null || dest == null){
        	 return null;
        }          
        if(!clazz.isAssignableFrom(orig.getClass())){
            return null;
        }
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                Object oldValue = field.get(orig);
                Object newValue = field.get(dest);
                System.out.println(field.getName() + "----" + oldValue);
                System.out.println(field + "----" + newValue);
                if(!java.lang.reflect.Modifier.isFinal(field.getModifiers())){
                    if(!(ignoreNull && oldValue == null)){
                        if(ignoreExist && newValue != null){
 
                        }else{
                            field.set(dest, oldValue);
                        }
                    }
                }
                field.setAccessible(false);
            } catch (Exception e) {
            }
        }
 
        if(clazz.getSuperclass() == Object.class){
            return dest;
        }
 
        return copyProperties(orig, dest, clazz.getSuperclass(), ignoreNull,ignoreExist);
    }
    
    

	public T getCurrent() {
		return current;
	}

	public void setCurrent(T current) {
		this.current = current;
	}

	public T getOriginal() {
		return original;
	}

	public void setOriginal(T original) {
		this.original = original;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值