Java 反射常用方法

Java 反射常用的方法

(1)把List 转化为Map

场景:系统中有一个字典类,是一个实体类,如下(省略了getter,setter方法):

Java代码   收藏代码
  1. /** 
  2.  * Data Dictionary Entity 
  3.  */  
  4. @Entity  
  5. @Table(name = "t_dictionary")  
  6. public class CommonDictionary implements Cloneable, Serializable {  
  7.   
  8.     private static final long serialVersionUID = 0x33d260729eadd26eL;  
  9.   
  10.     /** 
  11.      * 主键id 
  12.      */  
  13.     private Long id;  
  14.     /** 
  15.      * 组id 
  16.      */  
  17.     private String groupId;  
  18.     /** 
  19.      * 键<br />不能取值为key,因为key是关键字 
  20.      */  
  21.     private String key2;  
  22.     /** 
  23.      * 值 
  24.      */  
  25.     private String value;  
  26.     /** 
  27.      * 描述 
  28.      */  
  29.     private String description;  
  30.  public CommonDictionary clone() throws CloneNotSupportedException {  
  31.         return (CommonDictionary) super.clone();  
  32.     }  

 从数据库中查出的结果是List<CommonDictionary> anticounterfeit,我想把它转化为List,CommonDictionary  中的key2作为map的key,CommonDictionary 中的value作为map的value.

方法如下 :

Java代码   收藏代码
  1. /*** 
  2.      *  
  3.      * @param list 
  4.      * @param clazz 
  5.      * @param keyProperty : 该成员变量的值作为map的key 
  6.      * @param valueProperty : 该成员变量的值作为map的value 
  7.      * @return 
  8.      */  
  9.     public static Map<String,Object> parseObjectList(List list,Class clazz,String keyProperty,String valueProperty){  
  10.         Map<String,Object> map=new HashMap<String, Object>();  
  11.         for(int i=0;i<list.size();i++){  
  12.             Object obj=list.get(i);  
  13.             Field keyf =null;  
  14.             Field valuef =null;  
  15.             try {  
  16.                 keyf = clazz.getDeclaredField(keyProperty);  
  17.             } catch (NoSuchFieldException e) {  
  18.                 keyf= getSpecifiedField(clazz.getSuperclass()/* 
  19.                                                              * may be null if it is 
  20.                                                              * Object . 
  21.                                                              */, keyProperty);  
  22.                 // e.printStackTrace();  
  23.             }  
  24.             try {  
  25.                 valuef = clazz.getDeclaredField(valueProperty);  
  26.             } catch (NoSuchFieldException e) {  
  27.                 valuef= getSpecifiedField(clazz.getSuperclass()/* 
  28.                                                              * may be null if it is 
  29.                                                              * Object . 
  30.                                                              */, valueProperty);  
  31.                 // e.printStackTrace();  
  32.             }  
  33.             keyf.setAccessible(true);  
  34.             valuef.setAccessible(true);  
  35.             try {  
  36.                 map.put((String)keyf.get(obj), valuef.get(obj));  
  37.             } catch (IllegalArgumentException e) {  
  38.                 e.printStackTrace();  
  39.             } catch (IllegalAccessException e) {  
  40.                 e.printStackTrace();  
  41.             }  
  42.         }  
  43.         return map;  
  44.     }  

 依赖的方法:

Java代码   收藏代码
  1. /*** 
  2.      * Get Specified Field 
  3.      *  
  4.      * @param clazz 
  5.      * @param fieldName 
  6.      * @return 
  7.      */  
  8.     public static Field getSpecifiedField(Class<?> clazz, String fieldName) {  
  9.         Field f = null;  
  10.         if (ValueWidget.isNullOrEmpty(clazz)) {  
  11.             return null;  
  12.         }  
  13.         try {  
  14.             f = clazz.getDeclaredField(fieldName);  
  15.         } catch (NoSuchFieldException e) {  
  16.             return getSpecifiedField(clazz.getSuperclass()/* 
  17.                                                          * may be null if it is 
  18.                                                          * Object . 
  19.                                                          */, fieldName);  
  20.             // e.printStackTrace();  
  21.         }  
  22.         return f;  
  23.     }  

 使用实例:

Java代码   收藏代码
  1. List<CommonDictionary> anticounterfeit=DictionaryParam.getList(Constant2.DICTIONARY_GROUP_ANTICOUNTERFEIT_CODE);  
  2.         QrSettingsBean qrSettingsBean=new QrSettingsBean();  
  3.         Map<String,Object>map=ReflectHWUtils.parseObjectList(anticounterfeit, CommonDictionary.class"key2""value");  
  4. ReflectHWUtils.setObjectValue(qrSettingsBean, map);  
  5.         model.addAttribute("qrSettingsBean", qrSettingsBean);  

 

 

(2)把Map 转化为java对象,map的key对应对象的成员变量的名称

Java代码   收藏代码
  1. /*** 
  2.      * 利用反射设置对象的属性值. 注意:属性可以没有setter 方法. 
  3.      *  
  4.      * @param obj 
  5.      * @param params 
  6.      * @throws SecurityException 
  7.      * @throws NoSuchFieldException 
  8.      * @throws IllegalArgumentException 
  9.      * @throws IllegalAccessException 
  10.      */  
  11.     public static void setObjectValue(Object obj, Map<String, Object> params)  
  12.             throws SecurityException, NoSuchFieldException,  
  13.             IllegalArgumentException, IllegalAccessException {  
  14.         if (ValueWidget.isNullOrEmpty(params)) {  
  15.             return;  
  16.         }  
  17.         Class<?> clazz = obj.getClass();  
  18.         for (Iterator it = params.entrySet().iterator(); it.hasNext();) {  
  19.             Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it  
  20.                     .next();  
  21.             String key = entry.getKey();  
  22.             Object propertyValue = entry.getValue();  
  23.             if (ValueWidget.isNullOrEmpty(propertyValue)) {  
  24.                 continue;  
  25.             }  
  26.             Field name = getSpecifiedField(clazz, key);  
  27.             if (name != null) {  
  28.                 name.setAccessible(true);  
  29.                 name.set(obj, propertyValue);  
  30.             }  
  31.         }  
  32.   
  33.     }  
  34. /*** 
  35.      * Get Specified Field 
  36.      *  
  37.      * @param clazz 
  38.      * @param fieldName 
  39.      * @return 
  40.      */  
  41.     public static Field getSpecifiedField(Class<?> clazz, String fieldName) {  
  42.         Field f = null;  
  43.         if (ValueWidget.isNullOrEmpty(clazz)) {  
  44.             return null;  
  45.         }  
  46.         try {  
  47.             f = clazz.getDeclaredField(fieldName);  
  48.         } catch (NoSuchFieldException e) {  
  49.             return getSpecifiedField(clazz.getSuperclass()/* 
  50.                                                          * may be null if it is 
  51.                                                          * Object . 
  52.                                                          */, fieldName);  
  53.             // e.printStackTrace();  
  54.         }  
  55.         return f;  
  56.     }  

 

(3)把对象中 值为空字符串的成员变量 ,将其值改为null

Java代码   收藏代码
  1. /*** 
  2.      * 把对象中空字符串改为null 
  3.      * @param obj : 要修改的对象:java bean 
  4.      * @throws SecurityException 
  5.      * @throws NoSuchFieldException 
  6.      * @throws IllegalArgumentException 
  7.      * @throws IllegalAccessException 
  8.      */  
  9.     public static void convertEmpty2Null(Object obj)   
  10.             throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException{  
  11.         List<Field> fieldsList =getAllFieldList(obj.getClass());  
  12.         for(int i=0;i<fieldsList.size();i++){  
  13.             Field f=fieldsList.get(i);  
  14.             Object vObj=getObjectValue(obj,f );  
  15.             if(f.getType().getName().equals("java.lang.String") && (vObj instanceof String) ){  
  16.                 String str=(String)vObj;  
  17.                 if(SystemHWUtil.EMPTY.equals(str)){  
  18. //                  System.out.println(f.getName());  
  19. //                  System.out.println(f.getType().getName());  
  20.                     f.setAccessible(true);  
  21.                     f.set(obj, null);  
  22.                 }  
  23.             }  
  24.         }  
  25.     }  

 依赖的方法:

Java代码   收藏代码
  1. /*** 
  2.      * get all field ,including fields in father/super class 
  3.      *  
  4.      * @param clazz 
  5.      * @return 
  6.      */  
  7.     public static List<Field> getAllFieldList(Class<?> clazz) {  
  8.         List<Field> fieldsList = new ArrayList<Field>();// return object  
  9.         if (clazz == null) {  
  10.             return null;  
  11.         }  
  12.   
  13.         Class<?> superClass = clazz.getSuperclass();// father class  
  14.         if (!superClass.getName().equals(Object.class.getName()))/* 
  15.                                                                  * java.lang.Object 
  16.                                                                  */{  
  17.   
  18.             // System.out.println("has father");  
  19.             fieldsList.addAll(getAllFieldList(superClass));// Recursive  
  20.         }  
  21.         Field[] fields = clazz.getDeclaredFields();  
  22.         for (int i = 0; i < fields.length; i++) {  
  23.             Field field = fields[i];  
  24.             // 排除因实现Serializable 接口而产生的属性serialVersionUID  
  25.             if (!field.getName().equals("serialVersionUID")) {  
  26.                 fieldsList.add(field);  
  27.             }  
  28.         }  
  29.         return fieldsList;  
  30.     }  
  31. /*** 
  32.      * 获取指定对象的属性值 
  33.      *  
  34.      * @param obj 
  35.      * @param name 
  36.      *            :Field 
  37.      * @return 
  38.      * @throws SecurityException 
  39.      * @throws NoSuchFieldException 
  40.      * @throws IllegalArgumentException 
  41.      * @throws IllegalAccessException 
  42.      */  
  43.     public static Object getObjectValue(Object obj, Field name)  
  44.             throws SecurityException, NoSuchFieldException,  
  45.             IllegalArgumentException, IllegalAccessException {  
  46.   
  47.         // Field f = getSpecifiedField(obj.getClass(), name.getName());  
  48.         if (name == null) {  
  49.             System.out.println("[ReflectHWUtils.getObjectValue]"  
  50.                     + obj.getClass().getName() + " does not has field " + name);  
  51.             return null;  
  52.         }  
  53.         name.setAccessible(true);  
  54.         return name.get(obj);  
  55.     }  

 

(4)判断两个对象的属性值是否都相等.

Java代码   收藏代码
  1. /*** 
  2.      * 判断两个对象的属性值是否都相等. 
  3.      *  
  4.      * @param obj1 
  5.      * @param obj2 
  6.      * @param exclusiveProperties 
  7.      *            : 要过滤的属性 
  8.      * @return 
  9.      * @throws SecurityException 
  10.      * @throws IllegalArgumentException 
  11.      * @throws NoSuchFieldException 
  12.      * @throws IllegalAccessException 
  13.      */  
  14.     public static boolean isSamePropertyValue(Object obj1, Object obj2,  
  15.             List<String> exclusiveProperties) throws SecurityException,  
  16.             IllegalArgumentException, NoSuchFieldException,  
  17.             IllegalAccessException {  
  18.         List<Field> fieldsList = getAllFieldList(obj1.getClass());  
  19.         for (int i = 0; i < fieldsList.size(); i++) {  
  20.             Field f = fieldsList.get(i);  
  21.             if ((!ValueWidget.isNullOrEmpty(exclusiveProperties))  
  22.                     && exclusiveProperties.contains(f.getName())) {// 过滤掉,不比较  
  23.                 continue;  
  24.             }  
  25.             Object propertyValue1 = getObjectValue(obj1, f);  
  26.             Object propertyValue2 = getObjectValue(obj2, f);  
  27.   
  28.             System.out.println(f.getName());  
  29.             if (propertyValue1 == propertyValue2) {// if propertyValue1 is null  
  30.                 continue;  
  31.             }  
  32.             if (!isSameBySimpleTypes(propertyValue1, propertyValue2)) {  
  33.                 return false;  
  34.             }  
  35.         }  
  36.         return true;  
  37.     }  
  38.   
  39. /*** 
  40.      * 比较java 基本类型的值是否相同. 
  41.      *  
  42.      * @param obj1 
  43.      *            : String,Integer,Double,Boolean 
  44.      * @param obj2 
  45.      * @return 
  46.      */  
  47.     public static boolean isSameBySimpleTypes(Object obj1, Object obj2) {  
  48.         if (obj1 == obj2) {  
  49.             return true;  
  50.         }  
  51.         if (obj1 instanceof Integer) {// int  
  52.             Integer int1 = (Integer) obj1;  
  53.             Integer int2 = (Integer) obj2;  
  54.             return int1.intValue() == int2.intValue();  
  55.         } else if (obj1 instanceof Double) {// double  
  56.             Double double1 = (Double) obj1;  
  57.             Double double2 = (Double) obj2;  
  58.             return double1.compareTo(double2) == 0;  
  59.         } else if (obj1 instanceof Boolean) {// double  
  60.             Boolean boolean1 = (Boolean) obj1;  
  61.             Boolean boolean2 = (Boolean) obj2;  
  62.             return boolean1.compareTo(boolean2) == 0;  
  63.         } else if (obj1 instanceof String) {  
  64.             String str1 = (String) obj1;  
  65.             String str2 = (String) obj2;  
  66.             return str1.equals(str2);  
  67.         } else if (obj1 instanceof Timestamp) {  
  68.             Timestamp time1 = (Timestamp) obj1;  
  69.             Timestamp time2 = (Timestamp) obj2;  
  70.             return time1.compareTo(time2) == 0;  
  71.         } else if (obj1 instanceof java.util.Date) {  
  72.             java.util.Date time1 = (java.util.Date) obj1;  
  73.             java.util.Date time2 = (java.util.Date) obj2;  
  74.             return time1.compareTo(time2) == 0;  
  75.         } else if (obj1 instanceof java.sql.Date) {  
  76.             java.sql.Date time1 = (java.sql.Date) obj1;  
  77.             java.sql.Date time2 = (java.sql.Date) obj2;  
  78.             return time1.compareTo(time2) == 0;  
  79.         }  
  80.         return obj1 == obj2;  
  81.     }  
  82.   
  83. /*** 
  84.      * 获取指定对象的属性值 
  85.      *  
  86.      * @param obj 
  87.      * @param name 
  88.      *            :Field 
  89.      * @return 
  90.      * @throws SecurityException 
  91.      * @throws NoSuchFieldException 
  92.      * @throws IllegalArgumentException 
  93.      * @throws IllegalAccessException 
  94.      */  
  95.     public static Object getObjectValue(Object obj, Field name)  
  96.             throws SecurityException, NoSuchFieldException,  
  97.             IllegalArgumentException, IllegalAccessException {  
  98.   
  99.         // Field f = getSpecifiedField(obj.getClass(), name.getName());  
  100.         if (name == null) {  
  101.             System.out.println("[ReflectHWUtils.getObjectValue]"  
  102.                     + obj.getClass().getName() + " does not has field " + name);  
  103.             return null;  
  104.         }  
  105.         name.setAccessible(true);  
  106.         return name.get(obj);  
  107.     }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值