2015-05-30 44 views
2

以下是我的POJO类,它有50个带setter和getters的字段。如何从pojo动态获取字段

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条记录,有没有办法做到这一点动态(通过任何环)。

感谢

+3

只是好奇 - 为什么地球上你会有一个1000字段,而不是一个列表? – dnault

+1

您可以使用java反射 – Razib

+0

我认为反射远远超出了这个例子的范围。 –

回答

4

您可以使用Java反射。为简单起见,我假定您的Employee calss仅包含int字段。但是您可以使用此处使用的类似规则获取float,doublelong的值。这里是一个完整的代码 -

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

} 
+0

我认为他不知道如何使用数组,反射现在肯定是我们希望他学习数组或列表的地方。 –

1

是的,而不是每个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]; 
} 
+0

我只有字段,因为我使用的是spring批处理。 – User111

2

是,不使用1000领域!使用数组与1000元,然后填写array[i-1]mi你的类将是这样的:

Class Employee{ 
    int[] empArr = new int[1000]; 
} 

然后利用能找到的总和是这样的:

int sum = 0; 

for(int i = 0; i<1000 ; i++) 
    sum+= e1.empArr[i] 
+0

虽然你,但我从数据库中检索我的数据并存储在pojo中,所以我只需要使用pojo类 – User111

+0

因此,你有一张1000列的表格? – Ouney

3

我不可能想象一个真实的生活在一个班级中有1000个字段的场景。话虽如此,你可以反思地调用你所有的获得者。使用Introspector来完成这项任务:

int getEmployeeSum(Employee employee) 
{  
    int sum = 0; 
    for(PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(Employee.class).getPropertyDescriptors()) 
    { 
     sum += propertyDescriptor.getReadMethod().invoke(employee); 
    } 

    return sum; 
}