如何使用反射来查找类中使用的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

不需要反射。检查传递的数组和封闭类的字段是否相等就足够了:

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

相关内容

  • 没有找到相关文章