Ofir N
Ofir N

Reputation: 99

get arraylist size from object using reflection

I have a class which I want to analyze with java.reflection. I created a class that has an Arraylist of other object. When I want to analyze class which has the ArrayList the class is recongized but I dont know how to get the Arraylist size.

I attached the code.

public class Department { private ArrayList Students;

public Department() {
    super();
    Students = new ArrayList<>();
}
public Department(ArrayList<Student> students) {
    super();
    Students = students;
}
public void addStudent(Student student){
    if(student != null){
        this.Students.add(student);
    }

}
@Override
public String toString() {
    return "Class [Students=" + Students  + "]";
}


public static void analyze2(Object obj){
    Class c =  obj.getClass();
    Field[] fieldType= c.getDeclaredFields();
    ArrayList<?> ob = new ArrayList<>();
    System.out.println(obj.toString());

      for(Field field : fieldType){
          Class cd = field.getType();
          ob = (ArrayList<?>) cd.cast(ob);
          System.out.println(field.getName()+" "+ field.getType());
          System.out.println(ob.size());

      }
    }

Upvotes: 1

Views: 2622

Answers (2)

Pikalek
Pikalek

Reputation: 946

If you just want to get & invoke the size method via reflection without casting the object back to ArrayList, you can use Method.invoke():

    ArrayList<String> list = new ArrayList<>();
    list.add("A");
    list.add("B");

    Object obj = list;
    Class noparams[] = {};
    Class cls =  obj.getClass();

    // note may throw: NoSuchMethodException, SecurityException
    Method method = cls.getDeclaredMethod("size", noparams);
    method.setAccessible(true);

    // note may throw: IllegalAccessException, IllegalArgumentException,  InvocationTargetException
    Object retObj = method.invoke(obj, (Object[]) null);

    System.out.println(retObj);

I made a note of exceptions that need to be handled, but omitted exception handling specifics as it clutters the code & varies based on your specific context - do what's best for your situation.

Official tutorial: method invocation via reflection.

Upvotes: 1

Arun Iyer
Arun Iyer

Reputation: 54

You need to get the field value using the get method and pass the instance of the Department object. If the field is of type ArrayList, then cast the result to an 'ArrayList' and then print its size.

  for(Field field : fieldType){
      Class<?> cd = field.getType();
      Object fieldVal = field.get(ob);
      if(fieldVal instanceof ArrayList){
         ArrayList<?> arrayListField = (ArrayList<?>)fieldVal;
         System.out.println(arrayListField.size());
      }
      System.out.println(field.getName()+" "+ field.getType());
  }

Upvotes: 0

Related Questions