• 利用java反射原理写了一个简单赋值和取值通用类【改】


    拿ItTye上的machael的Code改的一个反射工具,改动主要在于:

    能支持 _fieldName 字段 与 getFieldName() 形式命名方法的对应。

      1 import java.lang.reflect.Field;
      2 import java.lang.reflect.Method;
      3 import java.text.SimpleDateFormat;
      4 import java.util.Date;
      5 import java.util.HashMap;
      6 import java.util.Locale;
      7 import java.util.Map;
      8 
      9 /**
     10  * java bean 反射工具
     11  */
     12 public class BeanRefUtil {
     13 
     14     /**
     15      * 取Bean的属性和值对应关系的MAP
     16      * @param bean
     17      * @return Map
     18      */
     19     public static Map<String, String> getFieldValueMap(Object bean) {
     20         Class<?> cls = bean.getClass();
     21         Map<String, String> valueMap = new HashMap<String, String>();
     22         // 取出bean里的所有方法
     23         Method[] methods = cls.getDeclaredMethods();
     24         Field[] fields = cls.getDeclaredFields();
     25 
     26         for (Field field : fields) {
     27             try {
     28                 String fieldType = field.getType().getSimpleName();
     29                 String fieldGetName = parGetName(field.getName());
     30                 if (!checkGetMet(methods, fieldGetName)) {
     31                     continue;
     32                 }
     33                 Method fieldGetMet = cls
     34                         .getMethod(fieldGetName, new Class[] {});
     35                 Object fieldVal = fieldGetMet.invoke(bean, new Object[] {});
     36                 String result = null;
     37                 if ("Date".equals(fieldType)) {
     38                     result = fmtDate((Date) fieldVal);
     39                 } else {
     40                     if (null != fieldVal) {
     41                         result = String.valueOf(fieldVal);
     42                     }
     43                 }
     44                 String fieldKeyName = parKeyName(field.getName());
     45                 valueMap.put(fieldKeyName, result);
     46             } catch (Exception e) {
     47                 continue;
     48             }
     49         }
     50         return valueMap;
     51 
     52     }
     53 
     54     /**
     55      * set属性的值到Bean
     56      * @param bean
     57      * @param valMap
     58      */
     59     public static void setFieldValue(Object bean, Map<String, String> valMap) {
     60         Class<?> cls = bean.getClass();
     61         // 取出bean里的所有方法
     62         Method[] methods = cls.getDeclaredMethods();
     63         Field[] fields = cls.getDeclaredFields();
     64 
     65         for (Field field : fields) {
     66             try {
     67 
     68                 String fieldSetName = parSetName(field.getName());
     69                 if (!checkSetMet(methods, fieldSetName)) {
     70                     continue;
     71                 }
     72                 Method fieldSetMet = cls.getMethod(fieldSetName, field
     73                         .getType());
     74                 String fieldKeyName = parKeyName(field.getName());
     75                 String value = valMap.get(fieldKeyName);
     76                 if (null != value && !"".equals(value)) {
     77                     String fieldType = field.getType().getSimpleName();
     78                     if ("String".equals(fieldType)) {
     79                         fieldSetMet.invoke(bean, value);
     80                     } else if ("Date".equals(fieldType)) {
     81                         Date temp = parseDate(value);
     82                         fieldSetMet.invoke(bean, temp);
     83                     } else if ("Integer".equals(fieldType)
     84                             || "int".equals(fieldType)) {
     85                         Integer intval = Integer.parseInt(value);
     86                         fieldSetMet.invoke(bean, intval);
     87                     } else if ("Long".equalsIgnoreCase(fieldType)) {
     88                         Long temp = Long.parseLong(value);
     89                         fieldSetMet.invoke(bean, temp);
     90                     } else if ("Double".equalsIgnoreCase(fieldType)) {
     91                         Double temp = Double.parseDouble(value);
     92                         fieldSetMet.invoke(bean, temp);
     93                     } else if ("Boolean".equalsIgnoreCase(fieldType)) {
     94                         Boolean temp = Boolean.parseBoolean(value);
     95                         fieldSetMet.invoke(bean, temp);
     96                     } else {
     97                         System.out.println("not supper type" + fieldType);
     98                     }
     99                 }
    100             } catch (Exception e) {
    101                 continue;
    102             }
    103         }
    104 
    105     }
    106 
    107     /**
    108      * 格式化string为Date
    109      * @param datestr
    110      * @return date
    111      */
    112     public static Date parseDate(String datestr) {
    113         if (null == datestr || "".equals(datestr)) {
    114             return null;
    115         }
    116         try {
    117             String fmtstr = null;
    118             if (datestr.indexOf(':') > 0) {
    119                 fmtstr = "yyyy-MM-dd HH:mm:ss";
    120             } else {
    121 
    122                 fmtstr = "yyyy-MM-dd";
    123             }
    124             SimpleDateFormat sdf = new SimpleDateFormat(fmtstr, Locale.UK);
    125             return sdf.parse(datestr);
    126         } catch (Exception e) {
    127             return null;
    128         }
    129     }
    130 
    131     /**
    132      * 日期转化为String
    133      * @param date
    134      * @return date string
    135      */
    136     public static String fmtDate(Date date) {
    137         if (null == date) {
    138             return null;
    139         }
    140         try {
    141             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
    142                     Locale.US);
    143             return sdf.format(date);
    144         } catch (Exception e) {
    145             return null;
    146         }
    147     }
    148 
    149     /**
    150      * 判断是否存在某属性的 set方法
    151      * @param methods
    152      * @param fieldSetMet
    153      * @return boolean
    154      */
    155     public static boolean checkSetMet(Method[] methods, String fieldSetMet) {
    156         for (Method met : methods) {
    157             if (fieldSetMet.equals(met.getName())) {
    158                 return true;
    159             }
    160         }
    161         return false;
    162     }
    163 
    164     /**
    165      * 判断是否存在某属性的 get方法
    166      * @param methods
    167      * @param fieldGetMet
    168      * @return boolean
    169      */
    170     public static boolean checkGetMet(Method[] methods, String fieldGetMet) {
    171         for (Method met : methods) {
    172             if (fieldGetMet.equals(met.getName())) {
    173                 return true;
    174             }
    175         }
    176         return false;
    177     }
    178 
    179     /**
    180      * 拼接某属性的 get方法
    181      * @param fieldName
    182      * @return String
    183      */
    184     public static String parGetName(String fieldName) {
    185         if (null == fieldName || "".equals(fieldName)) {
    186             return null;
    187         }
    188         int startIndex = 0;
    189         if(fieldName.charAt(0)=='_')
    190             startIndex = 1;
    191         return "get" + fieldName.substring(startIndex, startIndex + 1).toUpperCase()
    192                 + fieldName.substring(startIndex + 1);
    193     }
    194 
    195     /**
    196      * 拼接在某属性的 set方法
    197      * @param fieldName
    198      * @return String
    199      */
    200     public static String parSetName(String fieldName) {
    201         if (null == fieldName || "".equals(fieldName)) {
    202             return null;
    203         }
    204         int startIndex = 0;
    205         if(fieldName.charAt(0)=='_')
    206             startIndex = 1;
    207         return "set" + fieldName.substring(startIndex, startIndex + 1).toUpperCase()
    208                 + fieldName.substring(startIndex + 1);
    209     }
    210     
    211     /**
    212      * 获取存储的键名称(调用parGetName)
    213      * @param fieldName
    214      * @return 去掉开头的get
    215      */
    216     public static String parKeyName(String fieldName){
    217         String fieldGetName = parGetName(fieldName);
    218         if(fieldGetName != null 
    219                 && fieldGetName.trim() != "" 
    220                 && fieldGetName.length() > 3){
    221             return fieldGetName.substring(3);
    222         }
    223         return fieldGetName;
    224     }
    225 
    226 }
  • 相关阅读:
    升级到virtualbox2.1.4
    gentool 工具 modulerebuild
    解决man乱码问题
    关于HyperV的Linux驱动
    使用tmpfs优化firefox
    使用gmbox下载google歌曲
    升级到xorgserver1.5时出现的问题
    windows下使用where命令
    CSS中一些渐变效果与透明
    asp.net下密码框的一些小问题
  • 原文地址:https://www.cnblogs.com/moye/p/JavaReflectionBean.html
Copyright © 2020-2023  润新知