I have an object that I need to parse and intialize all fields of this object that are null and set all their string fields to "". The problem is when one of the fields of the object is List. then i need to create a new object of this sometype and call the method on it again. the field.getType() gives me interface list so I cant do field.getType().newInstance();
I tried getting type of the list and tried to create an instance out of it. but this gives me exception acessExcemption. Object obj1 = ((ParameterizedType) listType).getActualTypeArguments()[0].getClass().newInstance();
Field [] fields = segment.getClass().getDeclaredFields();
if (fields == null || fields.length < 0) {
log.info("Field Array Null or Empty");
}
for (Field field : fields){
if (field.getType().isAssignableFrom(List.class)) {
if ( field.get(segment) == null) {
log.info("++++++++++++++++++++++++ list is null +++++++++++++++++ = " + field.getName().getClass().getName() + " list type " + field.getType());
//field.set(segment, field.getType().newInstance());
//field.set(segment, (List<Object>) field.getType().newInstance());
List<Object> list = new ArrayList<>();
Type listType = field.getGenericType();
if (listType instanceof ParameterizedType) {
Type elementType = ((ParameterizedType) listType).getActualTypeArguments()[0];
log.info("............ element type of list ............" + elementType);
Object obj1 = elementType.getClass().newInstance(); //HERE FAILS TO CREATE INSTANCE OF LIST TYPE
list.add(obj1);
}
field.set(segment, list);
for (Object obj : (List)field.get(segment)) {
log.info("++++++++++++++++++++++++ list segment +++++++++++++++++ = " + obj.toString());
populateUnusedFields(obj);
}
}
I need to create a object of the someType of the list<>.
Aucun commentaire:
Enregistrer un commentaire