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

标签 java android reflection inner-classes

如何使用反射来确定哪个变量被传递到方法中?

示例

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

最佳答案

不需要反射(reflection)就能做到这一点。检查传递的数组和封闭类的字段是否相等就足够了:

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

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

关于java - 我如何使用反射来查找类中使用的 ArrayLIst 的类成员名称,例如?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17594130/

相关文章:

java - 当我尝试在类中使用 set() 函数时出错

java - 如何使用 Maven 中列为依赖项的包中的类?

Android Content Provider SQLite 连接表

java - 如何在 Android Room 中写一个到(两个嵌入式实体的许多 pojo)

java - 摆脱未经检查的反射

java - 使用 ifelse 语句修改 JSTL 中的代码

android - 创建 PhoneGap 3.0.0 项目错误 - 'platform add android' 我不是节点

java - JVM如何存储类的元信息?

java - 使用字节数组中的类而不进行反射?

java - Java中字节数组的位移位操作