Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1604022
  • 博文数量: 43
  • 博客积分: 169
  • 博客等级: 入伍新兵
  • 技术积分: 1162
  • 用 户 组: 普通用户
  • 注册时间: 2012-04-08 15:35
文章分类

全部博文(43)

文章存档

2021年(1)

2019年(4)

2016年(6)

2015年(8)

2013年(19)

2012年(5)

分类: Java

2013-04-11 08:41:02

通过反射机制为对象属性赋值


    

点击(此处)折叠或打开

  1. package com.cn.fanjg.rtti;

  2. import java.lang.reflect.Field;
  3. import java.lang.reflect.InvocationTargetException;
  4. import java.lang.reflect.Method;
  5. import java.util.regex.Matcher;
  6. import java.util.regex.Pattern;

  7. /**
  8.  * @function:
  9.  * @date : 2013-4-10 下午03:28:53
  10.  */
  11. @SuppressWarnings("rawtypes")
  12. public class AssignValueForAttributeUtil {
  13.     /** 正则表达式 用于匹配属性的第一个字母 {@value [a-zA-Z]} **/
  14.     private static final String REGEX = "[a-zA-Z]";
  15.     public static void setAttrributeValue(Object obj,String attribute,Object value)
  16.     {
  17.         String method_name = convertToMethodName(attribute,obj.getClass(),true);
  18.         Method[] methods = obj.getClass().getMethods();
  19.         for (Method method : methods) {
  20.             /**
  21.              *     因为这里只是调用bean中属性的set方法,属性名称不能重复
  22.              * 所以set方法也不会重复,所以就直接用方法名称去锁定一个方法
  23.              * (注:在java中,锁定一个方法的条件是方法名及参数)
  24.              * **/
  25.             if(method.getName().equals(method_name))
  26.             {
  27.                 Class[] parameterC = method.getParameterTypes();
  28.                 try {
  29.                     /**如果是基本数据类型时(如int、float、double、byte、char、boolean)
  30.                      * 需要先将Object转换成相应的封装类之后再转换成对应的基本数据类型
  31.                      * 否则会报 ClassCastException**/
  32.                     if(parameterC[0] == int.class)
  33.                     {
  34.                         method.invoke(obj,((Integer)value).intValue());
  35.                         break;
  36.                     }else if(parameterC[0] == float.class){
  37.                         method.invoke(obj, ((Float)value).floatValue());
  38.                         break;
  39.                     }else if(parameterC[0] == double.class)
  40.                     {
  41.                         method.invoke(obj, ((Double)value).doubleValue());
  42.                         break;
  43.                     }else if(parameterC[0] == byte.class)
  44.                     {
  45.                         method.invoke(obj, ((Byte)value).byteValue());
  46.                         break;
  47.                     }else if(parameterC[0] == char.class)
  48.                     {
  49.                         method.invoke(obj, ((Character)value).charValue());
  50.                         break;
  51.                     }else if(parameterC[0] == boolean.class)
  52.                     {
  53.                         method.invoke(obj, ((Boolean)value).booleanValue());
  54.                         break;
  55.                     }else
  56.                     {
  57.                         method.invoke(obj,parameterC[0].cast(value));
  58.                         break;
  59.                     }
  60.                 } catch (IllegalArgumentException e) {
  61.                     e.printStackTrace();
  62.                 } catch (IllegalAccessException e) {
  63.                     e.printStackTrace();
  64.                 } catch (InvocationTargetException e) {
  65.                     e.printStackTrace();
  66.                 } catch (SecurityException e) {
  67.                     e.printStackTrace();
  68.                 }
  69.             }
  70.         }
  71.     }
  72.     private static String convertToMethodName(String attribute,Class objClass,boolean isSet)
  73.     {
  74.         /** 通过正则表达式来匹配第一个字符 **/
  75.         Pattern p = Pattern.compile(REGEX);
  76.         Matcher m = p.matcher(attribute);
  77.         StringBuilder sb = new StringBuilder();
  78.         /** 如果是set方法名称 **/
  79.         if(isSet)
  80.         {
  81.             sb.append("set");
  82.         }else{
  83.         /** get方法名称 **/
  84.             try {
  85.                 Field attributeField = objClass.getDeclaredField(attribute);
  86.                 /** 如果类型为boolean **/
  87.                 if(attributeField.getType() == boolean.class||attributeField.getType() == Boolean.class)
  88.                 {
  89.                     sb.append("is");
  90.                 }else
  91.                 {
  92.                     sb.append("get");
  93.                 }
  94.             } catch (SecurityException e) {
  95.                 e.printStackTrace();
  96.             } catch (NoSuchFieldException e) {
  97.                 e.printStackTrace();
  98.             }
  99.         }
  100.         /** 针对以下划线开头的属性 **/
  101.         if(attribute.charAt(0)!='_' && m.find())
  102.         {
  103.             sb.append(m.replaceFirst(m.group().toUpperCase()));
  104.         }else{
  105.             sb.append(attribute);
  106.         }
  107.         return sb.toString();
  108.     }
  109.     public static Object getAttrributeValue(Object obj,String attribute)
  110.     {
  111.         String methodName = convertToMethodName(attribute, obj.getClass(), false);
  112.         Object value = null;
  113.         try {
  114.             /** 由于get方法没有参数且唯一,所以直接通过方法名称锁定方法 **/
  115.             Method methods = obj.getClass().getDeclaredMethod(methodName);
  116.             if(methods != null)
  117.             {
  118.                 value = methods.invoke(obj);
  119.             }
  120.         } catch (SecurityException e) {
  121.             e.printStackTrace();
  122.         } catch (NoSuchMethodException e) {
  123.             e.printStackTrace();
  124.         } catch (IllegalArgumentException e) {
  125.             e.printStackTrace();
  126.         } catch (IllegalAccessException e) {
  127.             e.printStackTrace();
  128.         } catch (InvocationTargetException e) {
  129.             e.printStackTrace();
  130.         }
  131.         return value;
  132.     }

  133. }

阅读(14947) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~