You can use reflection to solve your problem. As I don't know actually what you're gonna get and set from those two objects, I am giving a minimal example to show what you can do in this case.
You can get all the declared fields in your Summary
class as follows:
Field[] arrayOfFields = Summary.class.getDeclaredFields();
As you have all the fields of the class summary, you can iterate through each field and do the get and set easily for different objects of that class as follows. Remember to set field.setAccessible(true)
if the fields are private inside the class:
for (Field field: arrayOfFields) {
try {
field.setAccessible(true);
if (field.getType() == Double.class) {
Double prevVal = field.get(previous);
Double currentVal = field.get(current);
//do calculation and store to someval
field.set(resultSummary, someval);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
Well, you may need to check all type of classes that your class Summary
has and do the get and set according to that type. Please keep in mind that you cannot use primitive type fields for this if
condition check as they are not Class. So, you may need to convert the primitive type variables in the summary
class to corresponding Object Class. Like double
to Double
etc.
The field.get(Object obj)
method gets the value for the field in the Object obj
. Similarly, field.set(Object obj, Object value)
sets the Object value
to the field in the Object obj
With this approach you can achieve the goal easily with less hassle and dynamic coding.