1

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());

      }
    }

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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());
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.