Reputation: 95
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
Upvotes: 3
Views: 12545
Reputation: 11173
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);
}
}
Upvotes: 5
Reputation: 1646
I can't possibly imagine a real life scenario where you'd have 1000 fields in a class. Having said that, you can invoke all your getters reflectively. Use Introspector to accomplish this task:
int getEmployeeSum(Employee employee)
{
int sum = 0;
for(PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(Employee.class).getPropertyDescriptors())
{
sum += propertyDescriptor.getReadMethod().invoke(employee);
}
return sum;
}
Upvotes: 4
Reputation: 4805
Yes, dont use 1000 fields! use an array with 1000 elements, then fill array[i-1]
with mi
your class would be something like:
Class Employee{
int[] empArr = new int[1000];
}
then use could find sum like this:
int sum = 0;
for(int i = 0; i<1000 ; i++)
sum+= e1.empArr[i]
Upvotes: 2
Reputation: 4555
Yes, instead of having a separate variable for each m1, m2, m3, ... you can put them in one array like so:
Class Employee {
public int[] m = new int[1000];
}
Employee e1 = new Employee();
int total = 0;
for(int i = 0; i < e1.m.length; i++) {
total += e1.m[i];
}
Upvotes: 1