Java – how to dynamically get fields from POJOs
•
Java
The following 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 other 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 manually executing 50 records, there are any methods that can be dynamically (through any loop)
thank you
Solution
You can use java reflection For simplicity, I assume that your employee calcs contains only the int field However, you can use similar rules used here to get float, double, or long values This 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);
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
