2013-12-12 33 views
0

所以我叫測試類:Java中,獲得一類的所有變量值

public class Test{ 
    protected String name = "boy"; 
    protected String mainAttack = "one"; 
    protected String secAttack = "two"; 
    protected String mainType"three"; 
    protected String typeSpeak = "no spoken word in super class"; 

//Somehow put all the class variables in an Array of some sort 
    String[] allStrings = ??(all class' strings); 
//(and if you feel challenged, put in ArrayList without type declared. 
//So I could put in, not only Strings, but also ints etc.) 

    public void Tester(){ 
    //Somehow loop through array(list) and print values (for-loop?) 
    } 
} 

正如你所看到的,我希望把所有的類變量在數組中的ArrayList(或類似的東西)自動。 接下來我想能夠遍歷數組並打印/獲取值。 最好使用增強型for循環。

+0

使用getters和setter。 –

+0

爲什麼不直接使用數組呢?爲什麼你需要單獨的變量? –

+0

這是一個可怕的想法,千萬不要這樣設計你的課程。如果你只是爲了測試反射,那很好。 「反思」是關鍵詞。 –

回答

0

如果你真的需要這樣做,你需要使用反射。

然而,一個更好的方法是將值存儲在Map(可能是一個HashMap)中,然後你可以很容易地查詢/設置/ etc。

0

您可以使用MapHashmap存儲變量及其值,而不是ArrayArraylist

HashMap是一個對象,同時存儲「鍵/值」作爲對。在本文中,我們向您展示如何創建一個HashMap實例並迭代HashMap數據。

+0

我知道,你是對的。但在我的情況下,這不是我正在尋找的... – Ken

0

爲什麼不使用HashMap作爲值並遍歷該值?

Iterate through a HashMap

+0

我明白,而且你是正確的。但是,這並不適用於我現在的問題... – Ken

0

執行此操作。

String threeEleves = "sky"; 
String sevenDwarves = "stone"; 
String nineMortal = "die"; 
String oneRing[] = new String[] // <<< This 
{ 
    threeElves, 
    sevenDwarves, 
    nineMortal 
} 

或做

// in some class. 
public void process(final String... varArgs) 
{ 
    for (String current : varArgs) 
    { 
    } 
} 

String one = "noodles"; 
String two = "get"; 
String three = "in"; 
String four = "my"; 
String five = "belly"; 

process (one, two, three, four, five); 
0

至於對方說,不這樣做。但這是如何:

Class<?> cl = this.getClass(); 
List<Object> allObjects = new ArrayList<Object>(); 
for (java.lang.reflect.Field f: cl.getDeclaredFields()) 
{ 
    f.setAccessible(true); 
    try 
    { 
     Object o = f.get(this); 
     allObjects.add(o); 
    } 
    catch (Exception e) 
    { 
     ... 
    } 
} 
for (Object o: allObjects) 
    System.out.println(o); 
+0

我試過這個,但它不工作...好代碼雖然 – Ken

+0

這對我來說工作得很好。你能告訴我什麼行不通。 setAccessible在大多數情況下是至關重要的。 – geert3

相關問題