下面是我的POJO
类,它有50个带有setter和getter的字段。
Class Employee{
int m1;
int m2;
int m3;
.
.
int m50;
//setters and getters
从我的另一个类中我需要得到所有这50个字段来得到它们的和
Employee e1 =new Emploee();
int total = e1.getM1()+e2.getM2()+........e2.getM50();
除了对50条记录手动执行此操作之外,是否有任何方法可以动态执行(通过任何循环)
谢谢
您可以使用java反射。为简单起见,我假设您的Employee
类只包含int
字段。但是您可以使用这里用于获取float
、double
或long
值的类似规则。这里是一个完整的代码-
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);
}
}
我无法想象在一个类中有1000个字段的现实场景。话虽如此,您可以反射地调用所有getter。使用内省器完成此任务:
int getEmployeeSum(Employee employee)
{
int sum = 0;
for(PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(Employee.class).getPropertyDescriptors())
{
sum += propertyDescriptor.getReadMethod().invoke(employee);
}
return sum;
}
是的,不要使用1000个字段!使用包含1000个元素的数组,然后用mi
填充array[i-1]
,您的类将类似于:
Class Employee{
int[] empArr = new int[1000];
}
则可以找到如下sum:
int sum = 0;
for(int i = 0; i<1000 ; i++)
sum+= e1.empArr[i]
是的,而不是为每个m1, m2, m3,…你可以把它们放在一个数组中,像这样:
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];
}