Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate Field of type List using java reflection

I have a class called User which is having List of Account class objects like this

 public class User{
   private List<Account> accounts = new ArrayList<Account>();
 }

The Account object is having one transient field which i want to find and do some thing with that

public class Account{
  private transient openDateInOrgDateFormat;
}

This field i want to find using reflection and then check whether its transient then do something. Through reflection how to find field of type collection and then iterate that and to find if field inside the object which is in the list is transient or not.

like image 992
Pracheer Pancholi Avatar asked Dec 25 '22 00:12

Pracheer Pancholi


1 Answers

Since I don't know what exactly is stopping you from writing your code here are some tools which should be helpful:

  • to get array of fields declared in class use

    Field[] fields = User.class.getDeclaredFields()
    
  • to check what is the type assigned to field use field.getType().

  • to check if type is same as other type like List simply use

    type.equals(List.class);
    
  • to check if one type belongs to family of some ancestor (like List is subtype of Collection) use isAssignableFrom like

    Collection.class.isAssignableFrom(List.class)
    
  • to check modifiers of field like transient use

    Modifier.isTransient(field.getModifiers())
    
  • to access value held by field in specific instance, use

    Object value = field.get(instanceWithThatField)
    

    but in case of private fields you will need to make it accessible first via field.setAccessible(true). Then if you are sure about what type of object value holds you can cast it to that type like

    List<Account> list = (List<Account>) value;
    

    or do both operations in one line, like in your case

    List<Account> list = (List<Account>) field.get(userObject);
    

    which you can later iterate the way you want like
    for(Account acc : list){ /*handle each acc*/ }

like image 188
Pshemo Avatar answered Jan 06 '23 17:01

Pshemo