通过反射获取某个对象下的属性值,或通过父类获取

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * 通过反射获取某个对象下的属性值,或通过父类获取
 * User: wangyongfei
 * Date: 2016/8/10
 * Time: 9:56
 */
public class TestObjectRef {

    private static final Logger LOGGER = LoggerFactory.getLogger(TestObjectRef.class);

    /**
     * 对象相同
     * 对象属性name相同
     * @param list
     */
    public static Object object2Fields(List<Object>list,Object targetObject, String filteFieldName){
        for(Object sourceObject: list){
            Object rtnVal =  getObjectProprityValue(sourceObject, targetObject, filteFieldName);
            if(rtnVal == null){
                continue;
            }
            return rtnVal;
        }
        return null;
    }


    /**
     * 如果当前类查找不到,则从父类属性中查找
     * @param object 当前类
     * @param filteFieldName 查找字段
     * @return
     */
    public static Object getSupperClassPropertity(Object object,String filteFieldName){
        Class<?>clazz = object.getClass();
        if(clazz != null && clazz.getGenericSuperclass()!=null){
            Class claSupper = clazz.getSuperclass();
            return getProperty(claSupper, object,filteFieldName);
        }
        return null;
    }

    /**
     * 过滤父类中字段
     * @param _class
     * @param bean
     * @param filteFieldName
     * @return
     */
    private static Object getProperty(Class _class, Object bean, String filteFieldName) {
        Object obj = null;
        Field[] fields = _class.getDeclaredFields();
        //private调整为public
        Field.setAccessible(fields, true);
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            if (filteFieldName.equals(field.getName())) {
                try {
                    obj = field.get(bean);
                } catch (IllegalArgumentException e) {
                    LOGGER.error(e.getMessage());
                } catch (IllegalAccessException e) {
                    LOGGER.error(e.getMessage());
                }
                break;
            }
        }
        if (obj == null && _class.getGenericSuperclass() != null) {
            obj = getProperty(_class.getSuperclass(), bean, filteFieldName);
        }
        return obj;
    }



    /**
     * 获取过滤对象对应属性值
     *  // TODO: 2016/8/10  集合类型处理 list, map等 --待完善,目前已满足需求
     * @param sourceObject 数据源对象
     * @param targetObject 过滤目标对象
     * @param filteFieldName 过滤目标对象对应熟悉字段
     * @return
     */
    private static Object  getObjectProprityValue(Object sourceObject, Object targetObject, String filteFieldName)  {

        if(sourceObject == null || sourceObject.getClass() == null || filteFieldName == null || "".equalsIgnoreCase(filteFieldName)){
            return null;
        }
        Boolean flag = sameObjectInstance(sourceObject, targetObject);
        Field[] fields = sourceObject.getClass().getDeclaredFields();
        for(Field field: fields){
            String str = field.getName();
            Method m = null;
            try {
                m = sourceObject.getClass().getMethod("get" + str.substring(0, 1).toUpperCase()+""+str.substring(1, str.length()));
                try {
                    Object object = m.invoke(sourceObject);
                    if (!flag && validProperityType(field.getType().getName())) {//不是同一对象且类型为class,则继续迭代
                        Object rtnVal = getObjectProprityValue(object, targetObject, filteFieldName);
                        if(rtnVal == null){
                            continue;
                        }
                        return rtnVal;
                    } else {
                        if(flag){
                            if(filteFieldName.equalsIgnoreCase(field.getName())){
                                return object;
                            }
                        }
                        continue;
                    }

                } catch (IllegalAccessException e) {
                    LOGGER.info("对象转换处理异常, e:{}", e.getMessage());
                } catch (InvocationTargetException e) {
                    LOGGER.info("对象转换处理异常, e:{}", e.getMessage());
                }
            } catch (NoSuchMethodException e) {
                LOGGER.info("没有找到对应方法, e:{}", e.getMessage());
            }
        }

        //如果没找到,则从父类中查找
        if(flag){
            return  getSupperClassPropertity(sourceObject,filteFieldName);
        }
        return null;
    }

    /**
     * 校验两个对象是否属于同一对象实例
     * @param sourceObject
     * @param targetObject
     * @return
     */
    public static Boolean sameObjectInstance(Object sourceObject, Object targetObject){

        if(sourceObject == null || targetObject == null) return Boolean.FALSE;
        if(sourceObject.getClass().getName().equals(((Class) targetObject).getName())){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    /**
     * 类型校验方法
     * 1.以后如果出现特殊类型,在此方法中追加过滤即可
     * 2.目前只区分类与普通属性
     * 3.如果有特殊逻辑,可根据具体需要扩展此方法
     * @param type 类型值
     * @return
     */
    public static Boolean validProperityType(String type){

        if (type.equals("java.lang.String")) {
            return Boolean.FALSE;
        }
        if (type.equals("java.lang.Integer") || type.equals("int")) {
            return Boolean.FALSE;
        }
        if (type.equals("java.lang.Short")) {
            return Boolean.FALSE;
        }
        if (type.equals("java.lang.Double") || type.equals("double")) {
            return Boolean.FALSE;
        }
        if (type.equals("java.lang.Boolean") ||  type.equals("boolean")) {
            return Boolean.FALSE;
        }
        if (type.equals("java.util.Date")) {
            return Boolean.FALSE;
        }
        if (type.equals("java.util.List")) {
            return Boolean.FALSE;
        }
        if (type.equals("java.lang.Long") || type.equals("long")) {
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    public static Map<String, String> templateFormat(
            Map<String, List<String>> hashMap,
            Object... object) {

        if(hashMap == null || hashMap.size() <=0 ){
            return null;
        }
        List<Object>list = new ArrayList<>();
        Collections.addAll(list, object);
        Map<String, String> map = new HashMap<>();
        for(String key: hashMap.keySet()){
            try {
                Class<?> classType = Class.forName(key);
                for(String str: hashMap.get(key)) {
                    System.out.println(str+":" + object2Fields(list, classType, str));
                }
            } catch (ClassNotFoundException e) {
                LOGGER.warn("[模板格式转换]类查询异常,error:{}", e.getMessage());
            }
        }

        return  null;
    }
}

  

posted @ 2016-08-10 18:23  聊聊IT那些事  阅读(1462)  评论(0编辑  收藏  举报