2014-06-06 70 views
1

的實例變量我有一個類爪哇 - 循環,並通過一類

Class Test{ 

private String something ; 
private String somethingElse; 
private String somethingMore; 

} 

我創造了這樣的一個實例。

myInst = new Test(); 

並將值添加到第一和第二變量。

現在我需要檢查是否有任何變量爲空。

我知道我能做到這一點像if(myInst.something == null)

但我添加到類的每個項目是很難做到的。

有無論如何,我可以檢查實例通過循環所有元素,看到什麼是空的。

就像 -

for(i=0; i< myInstanceVariables ; i++) 
{ 

if(myInstanceVariable == null){ 

//do something 
donotDisplay(myInstanceVariable) 

} 

TIA

+0

你可以使用反射用於這些目的 – nikis

+0

通過反射::獲取變量名稱並循環它們並檢查該循環中的值?這裏有什麼問題? – NeverGiveUp161

回答

0

你必須使用反射過場之類的。

myInst = new Test(); 
for (Field field : myInst.getClass().getDeclaredFields()) 
    if (field.get(myInst) == null) 
    // do something 
2

您可以在實例中使用使用Fields的Reflection。在你的課堂上,添加這段代碼。它將採取所有的領域,並獲得他們的價值。

Field[] fields = getClass().getDeclaredFields(); // get all the fields from your class. 
for (Field f : fields) {       // iterate over each field... 
    try { 
     if (f.get(this) == null) {    // evaluate field value. 
      // Field is null 
     } 
    } catch (IllegalArgumentException ex) { 
     ex.printStackTrace(); 
    } catch (IllegalAccessException ex) { 
     ex.printStackTrace(); 
    } 
} 

這裏是一個示例代碼:https://ideone.com/58jSia

+0

您必須使用'getDeclaredFields()'而不是'getFields()'來獲取實例變量 –

+0

是的,我看到了:)。謝謝。 – lpratlong

0

您可以使用反射,但是,在你的情況你只有字符串值,因此它也將是有意義的使用HashMap(例如):

HashMap hm = new HashMap(); 
hm.put("something", "itsValue"); 
hm.put("somethingElse", null); 

現在你可以把儘可能多的價值,你想,並遍歷他們是這樣的:

Set set = hm.entrySet(); 
Iterator i = set.iterator(); 

while(i.hasNext()){ 
    Map.Entry me = (Map.Entry)i.next(); 
    System.out.println(me.getKey() + " : " + me.getValue()); 
} 
+0

它是有道理的,但字符串鍵不會在編譯時拋出錯誤,所以我個人更喜歡不使用這樣的解決方案時,可以不使用字符串鍵。 (這也是爲什麼我喜歡Annotation而不是框架中的XML配置)。 – lpratlong