samedi 2 avril 2016

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

      }
    }





Aucun commentaire:

Enregistrer un commentaire