java反射应用

来源:互联网 发布:2017剑灵捏脸数据龙女 编辑:程序博客网 时间:2024/06/08 01:01

 

  1. 通过java反射获取对象的属性(属性集合使用Map集合返回),对象中如果存在对象引用那么同样使用Map集合封装。
  2. 通过Map集合反向生成java对象,每个Map中都会有className的属性,它的值是这个对象的完全限定名,用于Map-Bean的生成。
  3. List、Map集合会转换为字符串的形式保存,具体格式可以按照个人喜好。
package com.huawei.ifos.subsys.ds.util;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.HashMap;import java.util.Hashtable;import java.util.List;import java.util.Map;import java.util.Set;import java.util.UUID;import java.util.Map.Entry;import com.huawei.ifos.subsys.api.model.UIElement;import com.huawei.oms.exception.OMSException;import com.huawei.oms.log.OMSLog;import com.huawei.oms.log.OMSLogFactory;/** * 本类将VO映射为map集合 *  * 使用本类的对象最好出现子类和父类有一样字段的情况,如果出现可能会出现这些属性取不到值。 *  * @author wuwei *  */public class SubsysObject2Map {    private static final OMSLog LOGGER = OMSLogFactory            .getLog(SubsysObject2Map.class);    /**     * 缓存所有的map对象     */    private static Map<String, SubsysObjectCache> voCache = new Hashtable<String, SubsysObjectCache>();    /**     * 缓存实体对象     */    private static Map<String, UIElement> controlCache = new Hashtable<String, UIElement>();    /**     * 清除缓存     */    public static void clearCache() {        voCache = new HashMap<String, SubsysObjectCache>();        controlCache = new HashMap<String, UIElement>();    }    /**     * 获取某个对象的属性值的map集合     *      * @param obj     *            某VO 对象     * @return 返回 属性-值 键值对     */    public static Map<String, Object> getProperties(Object obj) {        if (obj == null) {            LOGGER                    .debug("SubsysObject2Map.getProperties(Object obj)  obj is null ");            return null;        }        Map<String, Object> properties = new HashMap<String, Object>();        Class<?> c = obj.getClass();        getsuperProperties(properties, c, obj);        return properties;    }    /**     * 获取对象的属性和值     *      * @param properties     *            Map<String, Object>     * @param c     *            Class<?>     * @param obj     *            obj 用于获取属性值     */    public static void getsuperProperties(Map<String, Object> properties,            Class<?> c, Object obj) {        Class<?> superClass = c.getSuperclass();        if (c.getSuperclass() != null && c.getSuperclass() != Object.class) {            // 循环获取所有的父类的属性和值            getsuperProperties(properties, superClass, obj);        }        // 获取文件名        String className = c.getName();        properties.put("className", className); // 无论什么元素都会默认保存这个属性        SubsysObjectCache cacheVo = voCache.get(className);// 获取缓存中的对象        // 如果缓存中不为空则取缓存中的数据                 getsuperPropertiesByReflect(properties , c , obj);          }        /**     * 通过java反射获取对象的属性和值     * @param properties 属性Map     * @param c 目标对象Class     * @param obj  目标对象     */    public static void getsuperPropertiesByReflect(Map<String, Object> properties,            Class<?> c, Object obj) {                // 获取文件名        String className = c.getName();                SubsysObjectCache cacheVo = new SubsysObjectCache();                if (voCache.get(className) != null) {            cacheVo = voCache.get(className);        } else {            cacheVo.setClassName(className);            voCache.put(className, cacheVo);        }                        // 获取字段        Field field[] = c.getDeclaredFields();        if (field != null) {            for (int i = 0; i < field.length; i++) {                // 获取属性名称                String pro = field[i].getName();                Method m = getGetMethod(pro, obj.getClass()); // 获取当前属性的get方法                if (m == null) {                    continue;                }                Object childObj = getProValue(m, obj); // 获得属性值                Field f = field[i];                String fieldType = f.getType().toString();                ObjProperties objPro = new ObjProperties();// 属性对象 (缓存用)                objPro.setName(pro);                boolean baseType = false;// 该属性是否是基本类型                // 判断是否有引用类属性                if (assertObj(fieldType)) { // 如果是引用类型那么就继续获取引用类型的属性和值                    try {                        baseType = true;                        objPro.setClassType(f.getType());                        if (childObj != null) {                            Map<String, Object> childPro = new HashMap<String, Object>(); // 引用类型属性的属性和值                            getsuperProperties(childPro, f.getType(),                                    childObj);                            properties.put(fieldType, childPro);                            //如果属性是对象那么保存class名称                            properties.put(pro, fieldType);                        }                    } catch (IllegalArgumentException e) {                        LOGGER                                .debug("getsuperProperties() get childPro",                                        e);                    }                }                                /*                 * 暂时不启用(勿删)                 *                  *                 //List集合中放入的对象的属性解析                if ((childObj != null) && (childObj instanceof List)) {                    List<Object> childList = (List<Object>)childObj;                    if(!childList.isEmpty()) {                        Object item = childList.get(0);                        if (assertObj(item.getClass().toString())) {                            //如果是自定义类型                            Map<String, Object> childPro = new HashMap<String, Object>(); // 引用类型属性的属性和值                            getsuperProperties(childPro, f.getType(),                                    item);                                                        properties.put(item.getClass().toString() + " " + UUID.randomUUID(), childPro);                            continue;                        }                    }                                    }                 */                objPro.setBaseType(baseType);                // 将属性加入缓存中                cacheVo.getPros().add(objPro);                cacheVo.getGetMethod().put(pro, m);// get方法加入缓存中                properties.put(pro, childObj);            }        }                }        /**     * 判断对象是否是为自定义引用类型     *      * @param fieldType     *            String     * @return boolean     */    public static Boolean assertObj(String fieldType) {        if (fieldType.contains("class ") && !fieldType.contains(".String")                && !fieldType.contains(".Boolean")                && !fieldType.contains(".Number")                && !fieldType.contains(".Double")) {            if (!fieldType.contains("List") && !fieldType.contains("Map")) {                return true;            }        }        return false;    }        /**     * 获取属性的值     *      * @param m     *            get方法     * @param obj     *            对象     * @return 属性的值     */    private static Object getProValue(Method m, Object obj) {        Object childObj = null; // 属性值        try {            childObj = m.invoke(obj, new Object[0]);        } catch (IllegalArgumentException e1) {            LOGGER.debug("getsuperProperties() get childPro methodName is :" + m.getName(), e1);        } catch (IllegalAccessException e1) {            LOGGER.debug("getsuperProperties() get childPro methodName is :" + m.getName(), e1);        } catch (InvocationTargetException e1) {            LOGGER.debug("getsuperProperties() get childPro methodName is :" + m.getName(), e1);        }        return childObj;    }    /**     * 将map集合转换为VO对象     *      * @param map     *            Map<String,Object>     * @param toClass     *            Object     * @return Object     */    public static Object getMap2VO(Map<String, Object> map, Object toClass)            throws OMSException {        Object obj = toClass;        if (map == null) {            return null;        }        Set<Entry<String, Object>> entrySet = map.entrySet();        for (Entry<String, Object> entry : entrySet) {            String pro = entry.getKey();            if ((pro.contains("class ") && !pro.contains(".String"))                    || pro.equals("className") || pro.equals("controlId")) {                continue;            }            Method setPro = getSetMethod(pro, toClass.getClass());            if (setPro == null) {                continue;            }            Class<?>[] types = setPro.getParameterTypes();// 参数类型            String paraType = types[0].toString();// 获取参数类型名称            // 判断该属性是否是除String以外的引用类型 如果是的话则不赋值            if (paraType.contains("class ") && !paraType.contains(".String")                    && !paraType.contains(".Boolean")                    && !paraType.contains(".Number")                    && !paraType.contains("Array")                    && !paraType.contains("Double")) {                Map<String, Object> childMap = null;                try {                    if (map.get(pro) == null || map.get(pro).equals("")) {                        continue;                    }                    try {                        childMap = (Map<String, Object>) map.get(pro);                    } catch (Exception e) {                        LOGGER.debug("getMap2VO()    类型转换异常", e);                        continue;                    }                } catch (ClassCastException e) {                    continue;                }                String className = "";                // 获取子对象的类型                if (childMap.get("className") != null) {                    className = childMap.get("className").toString();                }                // 获取子对象                Object childObj = SubsysObject2Map.getObj(className);                // 获取子对象实例                Object intalnceChildObj = getMap2VO(childMap, childObj);                map.put(pro, intalnceChildObj);            }            try {                Object valueObj = map.get(pro);                if (!paraType.equals("class java.lang.String")) {                    if (paraType.equals("int")) {                        if (valueObj != null && !valueObj.equals("")) {                            try {                                int intvalue = Integer.parseInt(valueObj                                        .toString());                                setPro.invoke(toClass,                                        new Object[] {intvalue});                            } catch (NumberFormatException e) {                                LOGGER.error(                                        "getMap2VO()   NumberFormatException",                                        e);                            }                        }                        continue;                    }                    if (paraType.contains(".Boolean")                            || paraType.equals("boolean")) {                        if (valueObj != null && !valueObj.equals("")) {                            Boolean booleanValue = Boolean                                    .parseBoolean(valueObj.toString());                            setPro.invoke(toClass,                                    new Object[] {booleanValue});                        }                        continue;                    }                    if (paraType.contains(".Double")                            || paraType.equals("double")) {                        if (valueObj != null && !valueObj.equals("")) {                            double doubleValue = Double.parseDouble(valueObj                                    .toString());                            setPro                                    .invoke(toClass,                                            new Object[] {doubleValue});                        }                        continue;                    }                    if (paraType.contains(".Float") || paraType.equals("float")) {                        if (valueObj != null && !valueObj.equals("")) {                            float floatVlaue = Float.parseFloat(valueObj                                    .toString());                            setPro.invoke(toClass, new Object[] {floatVlaue});                        }                        continue;                    }                    if (paraType.contains("Map")) {                        if (valueObj != null && !valueObj.equals("")) {                            Map<?, ?> valueMap = (Map<?, ?>) valueObj;                            setPro.invoke(toClass, new Object[] {valueMap});                        }                        continue;                    }                    if (paraType.contains("List")) {                        if (valueObj != null && !valueObj.equals("")) {                            List<?> valueList = (List<?>) valueObj;                            setPro.invoke(toClass, new Object[] {valueList});                        }                        continue;                    }                    setPro.invoke(toClass, new Object[] {valueObj});                    continue;                }                setPro.invoke(toClass, new Object[] {valueObj});            } catch (ClassCastException e) {                LOGGER.error("强制类型转换错误");            } catch (IllegalArgumentException e) {                LOGGER.error("IllegalArgumentException");            } catch (IllegalAccessException e) {                LOGGER.error("IllegalAccessException");            } catch (InvocationTargetException e) {                LOGGER.error("InvocationTargetException");            } catch (RuntimeException e) {                LOGGER.error("RuntimeException");            }        }        return obj;    }    /**     * 根据保存的对象名称获取对象     *      * @param classPath     *            String     * @return Object     */    public static Object getObj(String classPath) {        Object obj = null;        // 如果缓存中存在这个对象        // UIElement uiElement = controlCache.get(classPath);        // if (uiElement != null) {        // obj = uiElement.clone();        // clearObj(obj);        // return obj;        // }        try {            Class<?> c = Class.forName(classPath);            try {                obj = c.newInstance();                // controlCache.put(classPath, (UIElement) obj);            } catch (InstantiationException e) {                LOGGER.error("getObj()", e);            } catch (IllegalAccessException e) {                LOGGER.error("getObj()", e);            }        } catch (ClassNotFoundException e) {            LOGGER.error("getObj()", e);        }        return obj;    }        /**     * 获取类得set方法     *      * @param pro     *            String     * @param objClass     *            Class<?>     * @return Method     */    private static Method getSetMethod(String pro, Class<?> objClass) {        Method method = null;        String className = objClass.getName();        // 获取缓存数据        SubsysObjectCache objCache = voCache.get(className);        if (objCache != null) {            // 获取该类的所有方法            Map<String, Method> setMethods = objCache.getSetMethod();            method = setMethods.get(pro);            if (method != null) {                return method;            }        } else {            objCache = new SubsysObjectCache();        }        Class<?>[] paraTypes = new Class[1];        try {            Field feld = objClass.getDeclaredField(pro);            paraTypes[0] = feld.getType();            StringBuffer sb = new StringBuffer();            sb.append("set");            sb.append(pro.substring(0, 1).toUpperCase());            sb.append(pro.substring(1));            method = objClass.getMethod(sb.toString(), paraTypes);            // 在这个缓存中会先缓存get方法 在缓存get方法的时候会创建这个类得缓存,一般情况下objCache不会为null            if (objCache != null) {                objCache.getSetMethod().put(pro, method);            }        } catch (SecurityException e) {            LOGGER.error("SecurityException", e);        } catch (NoSuchFieldException e) {            Class<?> superClass = objClass.getSuperclass();            if (superClass != null && superClass != Object.class) {                // 如果该类中没有获得这个get方法那么在父类中查找                method = getSetMethod(pro, superClass);            }        } catch (NoSuchMethodException e) {            LOGGER.info(objClass.getName() + "not search properties " + pro                    + "get method");        }        return method;    }    /**     * 获取get方法     *      * @param pro     *            String 属性名     * @param objClass     *            Class<?>     * @return Method     */    private static Method getGetMethod(String pro, Class<?> objClass) {        Method method = null;        try {            StringBuffer sb = new StringBuffer();            sb.append("get");            sb.append(pro.substring(0, 1).toUpperCase());            sb.append(pro.substring(1));            method = objClass.getMethod(sb.toString());        } catch (SecurityException e) {            LOGGER.error(objClass.getName() + "class unallowed " + pro                    + " to get menthod");        } catch (NoSuchMethodException e) {            LOGGER.info(objClass.getName() + " not search properties " + pro                    + " get method");        }        return method;    }    /**     * 清空对象的值     *      * @param obj     *            Object     */    public static void clearObj(Object obj) {        if (obj == null) {            LOGGER.error("clearObj()   参数obj  is   null");            return;        }        // 获取所有的属性        Map<String, Object> pros = getProperties(obj);        for (String pro : pros.keySet()) {            // 这两个属性是后台自动加上的,在VO中是不存在的            if (pro.equals("className") || pro.equals("controlId")) {                continue;            }            Method setPro = getSetMethod(pro, obj.getClass());            if (setPro == null) {                continue;            }            try {                Class<?>[] types = setPro.getParameterTypes();// 参数类型                String paraType = types[0].toString();// 获取参数类型名称                if (!paraType.equals("class java.lang.String")) {                    if (paraType.equals("int")) {                        setPro.invoke(obj, new Object[] {0});                        continue;                    }                    if (paraType.contains(".Boolean")                            || paraType.equals("boolean")) {                        setPro.invoke(obj, new Object[] {false});                        continue;                    }                    if (paraType.contains(".Double")                            || paraType.equals("double")) {                        setPro.invoke(obj, new Object[] {0});                        continue;                    }                    if (paraType.contains(".Float") || paraType.equals("float")) {                        setPro.invoke(obj, new Object[] {0});                        continue;                    }                }                setPro.invoke(obj, new Object[] {null});            } catch (IllegalArgumentException e) {                LOGGER.error("IllegalArgumentException", e);            } catch (IllegalAccessException e) {                LOGGER.error("IllegalAccessException", e);            } catch (InvocationTargetException e) {                LOGGER.error("InvocationTargetException", e);            }        }    }}