下面是我的 POJO
类,它有 50 个带有 setter 和 getter 的字段。
Class Employee{
int m1;
int m2;
int m3;
.
.
int m50;
//setters and getters
从我的另一个类(class),我需要获取所有这 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);
}
}
关于java - 如何动态地从pojo中获取字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30542460/