1.

 1 package com.zhoushun;
 2 import java.lang.reflect.Method;
 3 import java.lang.reflect.Field;
 4 import java.beans.PropertyDescriptor;
 5 
 6 public class PropertyUtil {
 7     @SuppressWarnings("unchecked")
 8     public static PropertyDescriptor getPropertyDescriptor(Class clazz, String propertyName) {
 9         StringBuffer sb = new StringBuffer();//构建一个可变字符串用来构建方法名称
10         Method setMethod = null;
11         Method getMethod = null;
12         PropertyDescriptor pd = null;
13         try {
14             Field f = clazz.getDeclaredField(propertyName);//根据字段名来获取字段
15             if (f!= null) {
16                 //构建方法的后缀
17                String methodEnd = propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
18                sb.append("set" + methodEnd);//构建set方法
19                setMethod = clazz.getDeclaredMethod(sb.toString(), new Class[]{ f.getType() });
20                sb.delete(0, sb.length());//清空整个可变字符串
21                sb.append("get" + methodEnd);//构建get方法
22                //构建get 方法
23                getMethod = clazz.getDeclaredMethod(sb.toString(), new Class[]{ });
24                //构建一个属性描述器 把对应属性 propertyName 的 get 和 set 方法保存到属性描述器中
25                pd = new PropertyDescriptor(propertyName, getMethod, setMethod);
26             }
27         } catch (Exception ex) {
28                 ex.printStackTrace();
29         }
30     
31         return pd;
32     }
33     
34     @SuppressWarnings("unchecked")
35     public static void setProperty(Object obj,String propertyName,Object value){
36         Class clazz = obj.getClass();//获取对象的类型
37         PropertyDescriptor pd = getPropertyDescriptor(clazz,propertyName);//获取 clazz 类型中的 propertyName 的属性描述器
38         Method setMethod = pd.getWriteMethod();//从属性描述器中获取 set 方法
39         try {
40             setMethod.invoke(obj, new Object[]{value});//调用 set 方法将传入的value值保存属性中去
41         }catch (Exception e){
42             e.printStackTrace();
43         }
44     }
45     
46     @SuppressWarnings("unchecked")
47     public static Object getProperty(Object obj, String propertyName){
48        Class clazz = obj.getClass();//获取对象的类型
49        PropertyDescriptor pd = getPropertyDescriptor(clazz,propertyName);//获取 clazz 类型中的 propertyName 的属性描述器
50        Method getMethod = pd.getReadMethod();//从属性描述器中获取 get 方法
51        Object value =null ;
52        try {
53            value = getMethod.invoke(clazz, new Object[]{});//调用方法获取方法的返回值
54        } catch (Exception e) {
55            e.printStackTrace();
56        }
57        return value;//返回值
58     }
59 }

 

 

2.

 1 public boolean setValue(Object objSet, Object objGet)
 2         throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, IntrospectionException
 3     {
 4         boolean flag = true;
 5         Field fields[] = objSet.getClass().getDeclaredFields();
 6         String value = "";
 7         String fieldNameGet = "";
 8         List list = new ArrayList();
 9         Field afield[];
10         int j = (afield = fields).length;
11         for(int i = 0; i < j; i++)
12         {
13             Field field = afield[i];
14             String fieldName = field.getName();
15             fieldNameGet = xmlToModel(fieldName);
16             if(!"error".equals(fieldNameGet))
17             {
18                 PropertyDescriptor pd = new PropertyDescriptor(fieldNameGet, objGet.getClass());
19                 Method getMethod = pd.getReadMethod();
20                 value = String.valueOf(getMethod.invoke(objGet, new Object[0]));
21                 boolean checkResult = returnMessage.checkValue(value, fieldNameGet);
22                 if(checkResult)
23                 {
24                     PropertyDescriptor pd1 = new PropertyDescriptor(fieldName, objSet.getClass());
25                     Method setMethod = pd1.getWriteMethod();
26                     setMethod.invoke(objSet, new Object[] {
27                         field.getType().getConstructor(new Class[] {
28                             java/lang/String
29                         }).newInstance(new Object[] {
30                             value
31                         })
32                     });
33                 } else
34                 {
35                     flag = checkResult;
36                 }
37             }
38         }
39 
40         return flag;
41     }

 

3.

 1 import java.beans.PropertyDescriptor;
 2 import java.lang.reflect.Field;
 3 import java.lang.reflect.Method;
 4 public class ReflectTest {
 5  
 6  public static void main(String[] args) throws Exception {
 7   Class clazz = Class.forName("TaskProvidePropsList");//这里的类名是全名。。有包的话要加上包名
 8   Object obj = clazz.newInstance();
 9   Field[] fields = clazz.getDeclaredFields();
10   //写数据
11   for(Field f : fields) {
12    PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);
13    Method wM = pd.getWriteMethod();//获得写方法
14    wM.invoke(obj, 2);//因为知道是int类型的属性,所以传个int过去就是了。。实际情况中需要判断下他的参数类型
15   }
16   //读数据
17   for(Field f : fields) {
18    PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);
19    Method rM = pd.getReadMethod();//获得读方法
20    Integer num = (Integer) rM.invoke(obj);//因为知道是int类型的属性,所以转换成integer就是了。。也可以不转换直接打印
21    System.out.println(num);
22   }
23  }
24 }

 

posted on 2017-11-20 23:23  Sharpest  阅读(440)  评论(0)    收藏  举报