在做导出Excel的时候,需要获取到集合类的值,一个一个获取代码量巨大,太浪费时间。为了提高代码的简洁性,重用性所以就想到了用java的反射机制去遍历集合类。然后在对这段代码进行了封装,就重复使用了。接下来看代码。
这里代码仅仅是遍历集合类,并没有是实现Excel的导出功能,不过是为了方便把集合类的输出到Excel表格。(在遍历成员变量的数组顺序是按封装的成员变量来的)
1. public class lianxi {
2. public static void main(String[] args) {
3. //调用demo
4. demo("com.ly.dao.test",test.class,kkkki());
5. }
6. public static <T> void demo(String lei,Class<T> t,List<T> list){
7. try {
8. Iterator each=list.iterator();
9. while (each.hasNext()) {
10. //类对象
11. T obj = (T) each.next();
12. //加载类
13. Class<?> class2=Class.forName(lei);
14. //获取成员变量
15. Field[] member=class2.getDeclaredFields();
16. //遍历成员变量
17. for (Field method : member) {
18. String memberName=method.getName();
19. //替换
20. String goRraces=memberName.replace("()", "");
21. //拼接get方法
22. String zaii="get"+goRraces.substring(0,1).toUpperCase()+goRraces.substring(1);
23. //需要调用的方法
24. Method method1=class2.getMethod(zaii);
25. //调用方法打印结果
26. System.out.println("结果值:"+method1.invoke(obj));
27. }
28. }
29. } catch (ClassNotFoundException e) {
30. // TODO Auto-generated catch block
31. e.printStackTrace();
32. } catch (NoSuchMethodException e) {
33. // TODO Auto-generated catch block
34. e.printStackTrace();
35. } catch (SecurityException e) {
36. // TODO Auto-generated catch block
37. e.printStackTrace();
38. } catch (IllegalAccessException e) {
39. // TODO Auto-generated catch block
40. e.printStackTrace();
41. } catch (IllegalArgumentException e) {
42. // TODO Auto-generated catch block
43. e.printStackTrace();
44. } catch (InvocationTargetException e) {
45. // TODO Auto-generated catch block
46. e.printStackTrace();
47. }
48. }
49. //模拟集合类的数据
50. public static List<test> kkkki(){
51. List<test> lists=new ArrayList<test>();
52. test t1=null;
53. for (int i = 0; i < 5; i++) {
54. t1=new test();
55. t1.setKk1(" i=" + i);
56. t1.setYyyy(i);
57. t1.setMm1(" i=" + i);
58. t1.setMm2(" i=" + i);
59. lists.add(t1);
60. }
61. return lists;
62. }
63. }
封装的test类
1. class test{
2. private int yyyy;
3. private String mm1;
4. private String kk1;
5. private String mm2;
6. public int getYyyy() {
7. return yyyy;
8. }
9. public void setYyyy(int yyyy) {
10. this.yyyy = yyyy;
11. }
12. public String getMm1() {
13. return mm1;
14. }
15. public void setMm1(String mm1) {
16. this.mm1 = mm1;
17. }
18. public String getKk1() {
19. return kk1;
20. }
21. public void setKk1(String kk1) {
22. this.kk1 = kk1;
23. }
24. public String getMm2() {
25. return mm2;
26. }
27. public void setMm2(String mm2) {
28. this.mm2 = mm2;
29. }
30. }
打印结果图: