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.
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 likefor(Account acc : list){ /*handle each acc*/ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With