简体   繁体   English

我如何使用反射为类中使用的ArrayLIst查找类成员名称,例如?

[英]how do i use reflection to find the class member name for an ArrayLIst that is used in the class, example?

how can i use reflection to determine which variable was passed into a method? 如何使用反射来确定将哪个变量传递给方法?

example

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

Don't need reflection to do that. 不需要反思就可以做到。 It's enough to check for equality of the passed array and enclosing class's fields: 检查传递的数组和封闭类的字段是否相等:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM