0

With below method I can pass any class and I can get values of the list.

public static void GetFieldName(ArrayList<Object> object)
            throws IllegalArgumentException, IllegalAccessException {

    for (Object obj : object)
        for (Field field : obj.getClass().getDeclaredFields()) {
            Log.i("Field", field.getName() + ":" + field.get(obj));

        }
    }

Suppose I have two classes Student and Employee. I don't know how many fields are there in both of them. Still I can get value of every field using the above method.

Now, I want to check if a particular class has any ArrayList within, i.e Suppose the Student class has an Arraylist<Address> of Address class. So can I get the array list values?

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
nil
  • 187
  • 1
  • 18

2 Answers2

1

You need to use the Class#isAssignableFrom(Class cls) method.

for (Field field : obj.getClass().getDeclaredFields()) {
    Log.i("Field", field.getName() + ":" + field.get(obj));
    if (field.getType().isAssignableFrom(ArrayList.class) {
        field.setAccessible(true); //needed for private fields 
        Object value = field.get(c); //getting the private field value
        ArrayList<Address> x = (ArrayList<Address>) value; // cast to ArrayList<Address>
    }
}

More info:

Community
  • 1
  • 1
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
0

You can call getDeclaringClass() on field object and compare it to desired class (e.g. ArrayList)

tomieq
  • 29
  • 1
  • 4