如何动态地从pojo中获取字段

Use*_*111 3 java variables field pojo

下面是我的POJO课程,其中有50个带有setter和getter的字段。

Class Employee{
int m1;
int m2;
int m3;
.
.
int m50;
//setters and getters
Run Code Online (Sandbox Code Playgroud)

在另一堂课中,我需要获得所有这50个字段的总和

Employee e1 =new Emploee();
int total = e1.getM1()+e2.getM2()+........e2.getM50();
Run Code Online (Sandbox Code Playgroud)

无需手动进行50条记录,而是可以通过任何循环动态地进行操作。

谢谢

Raz*_*zib 5

您可以使用Java反射。为简单起见,我假设您的Employee成绩只包含int字段。但是你可以使用这里用于获取类似的规则floatdoublelong价值。这是完整的代码-

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);
 }

}
Run Code Online (Sandbox Code Playgroud)