java 反射通过get方法获得属性值

java 反射通过get方法获得属性值

 来源:http://zgc168.iteye.com/blog/1633131

1、根据对象获得所有字段的值

Java代码   收藏代码
  1. public static void method(Object obj) {  
  2.     try {  
  3.         Class clazz = obj.getClass();  
  4.         Field[] fields = obj.getClass().getDeclaredFields();//获得属性  
  5.         for (Field field : fields) {  
  6.             PropertyDescriptor pd = new PropertyDescriptor(field.getName(),  
  7.                     clazz);  
  8.             Method getMethod = pd.getReadMethod();//获得get方法  
  9.             Object o = getMethod.invoke(obj);//执行get方法返回一个Object  
  10.             System.out.println(o);  
  11.         }  
  12.     } catch (SecurityException e) {  
  13.         e.printStackTrace();  
  14.     } catch (IllegalArgumentException e) {  
  15.         e.printStackTrace();  
  16.     } catch (IntrospectionException e) {  
  17.         e.printStackTrace();  
  18.     } catch (IllegalAccessException e) {  
  19.         e.printStackTrace();  
  20.     } catch (InvocationTargetException e) {  
  21.         e.printStackTrace();  
  22.     }  
  23. }  

  

 

 

2、通过对象和具体的字段名字获得字段的值

Java代码   收藏代码
  1. public static void method(Object obj, String filed) {  
  2.     try {  
  3.         Class clazz = obj.getClass();  
  4.         PropertyDescriptor pd = new PropertyDescriptor(filed, clazz);  
  5.         Method getMethod = pd.getReadMethod();//获得get方法  
  6.   
  7.         if (pd != null) {  
  8.   
  9.             Object o = getMethod.invoke(obj);//执行get方法返回一个Object  
  10.             System.out.println(o);  
  11.   
  12.         }  
  13.     } catch (SecurityException e) {  
  14.         e.printStackTrace();  
  15.     } catch (IllegalArgumentException e) {  
  16.         e.printStackTrace();  
  17.     } catch (IntrospectionException e) {  
  18.         e.printStackTrace();  
  19.     } catch (IllegalAccessException e) {  
  20.         e.printStackTrace();  
  21.     } catch (InvocationTargetException e) {  
  22.         e.printStackTrace();  
  23.     }  
  24. }  

你可能感兴趣的:(java,反射,属性取值)