I am new to reflection and trying to create a generalized function which will take in object and parse all the fields that are of type String, String[] or List<String>. Any String, String[] or List<String> that is present in nested object has also to be parsed. Is there any utility which can help me in doing that? Getting the values from parent object (User) was simple – used BeanUtils.describe(user); – it gives the String values in parent object but not String[], List<String> and nested object. I am sure I might not be the first one who needs this feature? Are there any utilities or code which could help me achieve do this?
public class User {
private String somevalue;
private String[] thisArray;
private List<String> thisList;
private UserDefinedObject myObject;
.
.
.
}
The method
Class.getDeclaredFieldswill get you an array ofFields representing each field of the class. You could loop over these and check the type returned byField.getType. Filtering fields of typeListtoList<String>is trickier – see this post for help with that.After doing the first dynamic lookup of the fields you want, you should keep track of (memoize) the relevant
Fieldobjects for better performance.Here’s a quick example:
Note that I used reference equality (
==) instead ofisAssignableFromto matchString.classandString[].classsinceStringisfinal.Edit: Just noticed your bit about finding nested
UserDefinedObjects. You could apply recursion to the above strategy in order to search for those.