2016-06-13 74 views
-1

我想檢索實例變量「customerId」的值。我有一組apis返回這個字段。在一些apis中,這個字段在基類下。在某些情況下,它嵌套在下面的幾個級別。有沒有辦法通過字段名稱「customerId」獲取值,而不考慮實例變量的位置?Java反射 - 獲取嵌套類中字段的值

如:

Customer 
    customerId 

Order 
Customer 
    customerId 

Account 
Order 
    customerId 

回答

0

試試這個:

public static Map<Field, Integer> getFieldWithName(Object o, Map<Field, Integer> list) throws IllegalAccessException { 
    Class<?> c = o.getClass(); 
    for(Field field : c.getDeclaredFields()) { 
     if(field.getName().equals("customerId") && field.getType().equals(int.class)) { 
      list.put(field, field.getInt(o)); 
     } else { 
      if(!field.isAccessible()) { 
       field.setAccessible(true); 
      } 
      getFieldWithName(field.get(o), list); 
     } 

    } 
    return list; 
} 

這將返回名爲customerId的領域和存儲在此字段中的值的Map。 GL!

+0

請注意,在循環引用存在的情況下,此代碼將產生一個異常,之後將命名該網站。當'customerId'在'o'的超類中聲明時,它也不會處理這種情況。它很容易出現'NullPointerException'。 – user3707125

+0

沒錯,只是想表明它是如何完成的。 – STersteeg

+0

謝謝,將盡力 –