I want to create a list using the fields in FhExtra
and other fields in the FhExtraImportResults
. There are many fields in this class; I just put few. I cannot edit FhExtraImportResults
and FhExtra
because they are used in other places.
I am trying to create new list and setting the fields manually. Is there any better way to create a new list with these fields?
The object I am receiving to convert is a List
of FhExtraImportResults
.
public class FhExtraImportResults {
FhExtra record;
String error;
Long loanId;
}
@Data
public class FhExtra {
String LoanNumber;
String FILoanNumber;
}
My expected list object looks like
[{
LoanNumber : 123
FILoanNumber : 321
error : NA
loanId : 456
}]
You could use a map of fields vs values using reflection like:
import java.lang.reflect.*;
import java.util.*;
public class MyClass {
public static void main(String args[]) throws IllegalAccessException {
MyClass.FhExtraImportResults obj = new MyClass.FhExtraImportResults();
obj.loanId = 456L;
obj.error = "NA";
obj.record = new MyClass.FhExtra();
obj.record.LoanNumber = "123";
obj.record.FILoanNumber = "321";
Map<String, Object> map = getObjectAllowedFields(obj);
System.out.println(map);
}
private static Map<String, Object> getObjectAllowedFields(Object obj) throws IllegalAccessException {
Map<String, Object> map = new HashMap<>();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field: fields) {
field.setAccessible(true);
Object value = getObjValue(obj, field);
if (value != null) {
if(value instanceof Map){
map.putAll((Map<String, Object>) value);
} else {
map.put(field.getName(), value);
}
}
}
return map;
}
private static Object getObjValue(Object obj, Field field) throws IllegalAccessException {
Class<?> type = field.getType();
if (type.getTypeName().equals(MyClass.FhExtra.class.getTypeName()))
return getObjectAllowedFields(field.get(obj));
if (type.getTypeName().startsWith("java.lang"))
return field.get(obj);
// Add more types here or filter by field name.
return null;
}
public static class FhExtraImportResults {
FhExtra record;
String error;
Long loanId;
}
public static class FhExtra {
String LoanNumber;
String FILoanNumber;
}
}
{error=NA, FILoanNumber=321, loanId=456, LoanNumber=123}
Note that downsides of this solution are that it will override entries with the same key from the nested objects if any (which can be fixed by amending the parent field name) and reflection is a bit slow