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

来源:互联网 发布:我的世界pe拔刀剑js 编辑:程序博客网 时间:2024/06/05 18:44
1、根据对象获得所有字段的值
public static void method(Object obj) {
     try {
          Class clazz = obj.getClass();
          Field[] fields = obj.getClass().getDeclaredFields();//获得属性
          for (Field field : fields) {
               PropertyDescriptor pd = new PropertyDescriptor(field.getName(),
                         clazz);
               Method getMethod = pd.getReadMethod();//获得get方法
               Object o = getMethod.invoke(obj);//执行get方法返回一个Object
               System.out.println(o);
          }
     } catch (SecurityException e) {
          e.printStackTrace();
     } catch (IllegalArgumentException e) {
          e.printStackTrace();
     } catch (IntrospectionException e) {
          e.printStackTrace();
     } catch (IllegalAccessException e) {
          e.printStackTrace();
     } catch (InvocationTargetException e) {
          e.printStackTrace();
     }
}


2、通过对象和具体的字段名字获得字段的值
public static void method(Object obj, String filed) {
     try {
          Class clazz = obj.getClass();
          PropertyDescriptor pd = new PropertyDescriptor(filed, clazz);
          Method getMethod = pd.getReadMethod();//获得get方法


          if (pd != null) {


               Object o = getMethod.invoke(obj);//执行get方法返回一个Object
               System.out.println(o);


          }
     } catch (SecurityException e) {
          e.printStackTrace();
     } catch (IllegalArgumentException e) {
          e.printStackTrace();
     } catch (IntrospectionException e) {
          e.printStackTrace();
     } catch (IllegalAccessException e) {
          e.printStackTrace();
     } catch (InvocationTargetException e) {
          e.printStackTrace();
     }
}
0 0
原创粉丝点击