2013-07-11 55 views
0

如何使用反射來確定將哪個變量傳遞給方法?如何使用反射來查找類中使用的ArrayLIst的類成員名稱,例如?

例如

public class ExampleClass { 

    // class member variables 
    ArrayList<String> strArrayOne; 
    ArrayLIst<String> strArrayTwo; 

    //constructor 
    public ExampleClass()[ 
    strArrayOne = new ArrayList<String>(); 
    strArrayTwo = new ArrayList<String>(); 
    } 

    // create instance of nested class passing in the required ArrayList in constructor 
    NestedInnerClass testInstance = new NestedInnerClass(strArrayOne); 

    // nested inner class 
    public class NestedInnerClass{ 

    // class member variable 
    ArrayList<String> memberArray = new ArrayList<String>(); 

    // constructor 
    public NestedInnerClass(ArrayList<String> inputArray){ 
     memberArray = inputArray; 

     // put code here to determine with reflection which of the 
     // two outer class variables is being passed in strArrayOne or strArrayTwo? 
    } 

    } // end nested inner class 

} // end outer class 
+1

爲什麼反射? 'inputArray == strArrayOne'應該足夠了 – Selvin

+0

此外,爲什麼不在內部類方法中使用實際的成員變量? – weltraumpirat

+0

這些都是很好的問題,我想這個工作比反思有更好的工具。 – Kevik

回答

1

不需要反射來做到這一點。這足以檢查傳遞的數組是否相等並封閉類的字段:

if (Arrays.equals(inputArray, ExampleClass.this.strArrayOne)) { 
    // first one has been passed 
} 

if (Arrays.equals(inputArray, ExampleClass.this.strArrayTwo)) { 
    // second one has been passed 
} 
相關問題