反射使用筆記

1.獲得object對象對應的所有已申明的屬性,包括public、private、和protected。

Field[] fields = objValue.getClass().getDeclaredFields();

2.獲得object對象對應的所有public的屬性

Field[] fields = objValue.getClass().getFields();

3.獲得屬性名稱

fields[i].getName();

4.獲得屬性值

 field.get(object);//這個反射出來的object對象中獲取所屬的值

5.從反射出的對象中獲取指定的屬性

Field field =  objValue.getClass().getDeclaredField("id") 

6.解決問題

如果從反射出的對象中獲取其私有方法或私有屬性,會報如下異常:

java.lang.IllegalAccessException: Class com.x.tmp.logger.OperateLogAspect can not access a member of class com.x.domain.entity.po.XxxPo with modifiers "private"

解決該問題,需要在使用反射對象前設置 field.setAccessible(true);目的在於:在使用反射的對象時取消 Java 語言訪問檢查。

Field[] fields = objValue.getClass().getDeclaredFields();
    for(Field field:fields){
          field.setAccessible(true);
          String name = field.getName();
          if("id".equals(name)){
              entityId = Integer.valueOf(field.get(objValue).toString());
              break;
          }
      }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章