2013-12-11 153 views
-1

我在該對象中有一個對象,我有近30個屬性,我想從對象中獲取所有的null屬性。從對象獲取null屬性

現在我正在通過if條件爲每個屬性單獨做這個,所以我的代碼是非常大的有沒有辦法在Java中從對象中獲得空屬性。

請幫忙得到它。

編輯上傳我的數據我想向用戶顯示空字段作爲錯誤消息。

+1

你可以使用反射,但你爲什麼要這樣做? –

+1

您可以使用[Reflection](http://docs.oracle.com/javase/tutorial/reflect/)。 –

+0

向下選民請提供相關信息,以便我可以學習 –

回答

4

這是如何使用反射得到所有的空字段:

YourClassObject objectToIntrospect = new YourClassObject(); 
    for (Field field : objectToIntrospect.getClass().getDeclaredFields()) { 
     field.setAccessible(true); // to allow the access of member attributes 
     Object attribute = field.get(objectToIntrospect); 
     if (attribute == null) { 
      System.out.println(field.getName() + "=" + attribute); 
     } 
    } 
+1

如果他們沒有這樣做的動機,很難讓新用戶遵守規則。只是給這些可憐的問題提供代碼並不會一般來說對網站沒有積極影響(在我看來)。 –

+3

@JeroenVannevel我同意你的評論,但部分。這取決於問題的類型。如果有什麼東西太容易用文字解釋,那麼我會選擇這條路。但有時使用代碼來描述事物更容易。這個問題聽起來很簡單,並回答說,使用反射你可以做到這一點也是一個公平的聲明。但根據我的經驗,沒有很多精通反射的Java編碼人員。在這種情況下,考慮到概念本身的複雜性,我想用代碼代替文本。我重視您的意見,並會盡可能考慮。 –

+0

夠公平的,你有一個觀點。如果提問者表現出了努力,我會更喜歡,但是你的推理是有道理的。 –

3

首先,你需要的Fields。然後你get the values,然後當值爲null時加上field name。所以,像這樣 -

public static String[] getNullFields(Object obj) { 
    List<String> al = new ArrayList<String>(); 
    if (obj != null) {    // Check for null input. 
    Class<?> cls = obj.getClass(); 
    Field[] fields = cls.getFields(); 
    for (Field f : fields) { 
     try { 
     if (f.get(obj) == null) { // Check for null value. 
      al.add(f.getName()); // Add the field name. 
     } 
     } catch (IllegalArgumentException e) { 
     e.printStackTrace(); 
     } catch (IllegalAccessException e) { 
     e.printStackTrace(); 
     } 
    } 
    } 
    String[] ret = new String[al.size()]; // Create a String[] to return. 
    return al.toArray(ret);    // return as an Array. 
}