下面是我的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);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句