Below is my POJO
class which has 50 fields with setters and getters.
Class Employee{
int m1;
int m2;
int m3;
.
.
int m50;
//setters and getters
From my another class I need to get all these 50 fields to get their sum
Employee e1 =new Emploee();
int total = e1.getM1()+e2.getM2()+........e2.getM50();
Instead of doing this manually for 50 records is there any way to do it dynamically(by any loop).
Thanks
You may use java reflection. For simplicity I assume your Employee
calss only contains int
field. But you can use the similar rules used here for getting float
, double
or long
value. Here is a complete code -
import java.lang.reflect.Field;
import java.util.List;
class Employee{
private int m=10;
private int n=20;
private int o=25;
private int p=30;
private int q=40;
}
public class EmployeeTest{
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException{
int sum = 0;
Employee employee = new Employee();
Field[] allFields = employee.getClass().getDeclaredFields();
for (Field each : allFields) {
if(each.getType().toString().equals("int")){
Field field = employee.getClass().getDeclaredField(each.getName());
field.setAccessible(true);
Object value = field.get(employee);
Integer i = (Integer) value;
sum = sum+i;
}
}
System.out.println("Sum :" +sum);
}
}