java类的反射的应用

来源:互联网 发布:江苏省域名备案 编辑:程序博客网 时间:2024/06/05 12:12

如果直接把excel表格中的数据导入数据库,首先应该将excel中的数据读取出来。

为了实现代码重用,所以使用了Object,而最终的结果是要获取一个list如List<User>、List<Book>等,所以需要使用泛型机制去实现。下面会给出代码,可能会稍微复杂一点,但注释很清晰,希望大家耐心阅读。

在上代码之前简单说一下思路:

        1.excel表格必须有表头,且表头中各列的值要与实体类的属性相同;

        2.先读取表头信息,然后获取表头列数,接着确定需要使用的set方法的名称,并存到数组中;

        3.利用反射机制,获取object对象的属性,通过与excel表格表头对比,确定各个属性的类型,存到数组中(以excel表格中属性的顺序);

        4.遍历除表头行的数据,利用反射机制实例化对象,调用对应的set方法,方法参数通过3获取;

上代码:(需要使用poi包,请自行下载)

实体类User:

[java] view plain copy


  1. public class User {  
  2.     private int id;  
  3.     private String name;  
  4.     private String password;  
  5.     public int getId() {  
  6.         return id;  
  7.     }  
  8.     public void setId(int id) {  
  9.         this.id = id;  
  10.     }  
  11.     public String getName() {  
  12.         return name;  
  13.     }  
  14.     public void setName(String name) {  
  15.         this.name = name;  
  16.     }  
  17.     public String getPassword() {  
  18.         return password;  
  19.     }  
  20.     public void setPassword(String password) {  
  21.         this.password = password;  
  22.     }  
  23.         



处理类:

[java] view plain copy
  1. package module.system.common;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.IOException;  
  7. import java.lang.reflect.Field;  
  8. import java.lang.reflect.Method;  
  9. import java.util.ArrayList;  
  10. import java.util.List;  
  11.   
  12. import org.apache.poi.hssf.usermodel.HSSFRow;  
  13. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  14. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  15.   
  16. /** 
  17.  * 从excel读取数据/往excel中写入 excel有表头,表头每列的内容对应实体类的属性 
  18.  *  
  19.  * @author nagsh 
  20.  *  
  21.  */  
  22. public class ExcelManage {  
  23.     private HSSFWorkbook workbook;  
  24.   
  25.     public ExcelManage(String fileDir) {  
  26.         File file = new File(fileDir);  
  27.         try {  
  28.             workbook = new HSSFWorkbook(new FileInputStream(file));  
  29.         } catch (FileNotFoundException e) {  
  30.             e.printStackTrace();  
  31.         } catch (IOException e) {  
  32.             e.printStackTrace();  
  33.         }  
  34.     }  
  35.   
  36.     /** 
  37.      * 读取excel表中的数据. 
  38.      *  
  39.      * @param sheetName 
  40.      *            表格索引(EXCEL 是多表文档,所以需要输入表索引号,如sheet1) 
  41.      */  
  42.     public List readFromExcel(String sheetName, Object object) {  
  43.   
  44.         List result = new ArrayList();  
  45.         // 获取该对象的class对象  
  46.         Class class_ = object.getClass();  
  47.         // 获得该类的所有属性  
  48.         Field[] fields = class_.getDeclaredFields();  
  49.   
  50.         // 读取excel数据  
  51.         // 获得指定的excel表  
  52.         HSSFSheet sheet = workbook.getSheet(sheetName);  
  53.         // 获取表格的总行数  
  54.         int rowCount = sheet.getLastRowNum() + 1// 需要加一  
  55.         if (rowCount < 1) {  
  56.             return result;  
  57.         }  
  58.         // 获取表头的列数  
  59.         int columnCount = sheet.getRow(0).getLastCellNum();  
  60.         // 读取表头信息,确定需要用的方法名---set方法  
  61.         // 用于存储方法名  
  62.         String[] methodNames = new String[columnCount]; // 表头列数即为需要的set方法个数  
  63.         // 用于存储属性类型  
  64.         String[] fieldTypes = new String[columnCount];  
  65.         // 获得表头行对象  
  66.         HSSFRow titleRow = sheet.getRow(0);  
  67.         // 遍历  
  68.         for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) { // 遍历表头列  
  69.             String data = titleRow.getCell(columnIndex).toString(); // 某一列的内容  
  70.             String Udata = Character.toUpperCase(data.charAt(0))  
  71.                     + data.substring(1, data.length()); // 使其首字母大写  
  72.             methodNames[columnIndex] = "set" + Udata;  
  73.             for (int i = 0; i < fields.length; i++) { // 遍历属性数组  
  74.                 if (data.equals(fields[i].getName())) { // 属性与表头相等  
  75.                     fieldTypes[columnIndex] = fields[i].getType().getName(); // 将属性类型放到数组中  
  76.                 }  
  77.             }  
  78.         }  
  79.         // 逐行读取数据 从1开始 忽略表头  
  80.         for (int rowIndex = 1; rowIndex < rowCount; rowIndex++) {  
  81.             // 获得行对象  
  82.             HSSFRow row = sheet.getRow(rowIndex);  
  83.             if (row != null) {  
  84.                 Object obj = null;  
  85.                 // 实例化该泛型类的对象一个对象  
  86.                 try {  
  87.                     obj = class_.newInstance();  
  88.                 } catch (Exception e1) {  
  89.                     e1.printStackTrace();  
  90.                 }  
  91.   
  92.                 // 获得本行中各单元格中的数据  
  93.                 for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {  
  94.                     String data = row.getCell(columnIndex).toString();  
  95.                     // 获取要调用方法的方法名  
  96.                     String methodName = methodNames[columnIndex];  
  97.                     Method method = null;  
  98.                     try {  
  99.                         // 这部分可自己扩展  
  100.                         if (fieldTypes[columnIndex].equals("java.lang.String")) {  
  101.                             method = class_.getDeclaredMethod(methodName,  
  102.                                     String.class); // 设置要执行的方法--set方法参数为String  
  103.                             method.invoke(obj, data); // 执行该方法  
  104.                         } else if (fieldTypes[columnIndex].equals("int")) {  
  105.                             method = class_.getDeclaredMethod(methodName,  
  106.                                     int.class); // 设置要执行的方法--set方法参数为int  
  107.                             double data_double = Double.parseDouble(data);  
  108.                             int data_int = (int) data_double;  
  109.                             method.invoke(obj, data_int); // 执行该方法  
  110.                         }  
  111.                     } catch (Exception e) {  
  112.                         e.printStackTrace();  
  113.                     }  
  114.                 }  
  115.                 result.add(obj);  
  116.             }  
  117.         }  
  118.         return result;  
  119.     }  
  120.   
  121.     public static void main(String[] args) {  
  122.         ExcelManage em = new ExcelManage("E:/test.xls");  
  123.         User user = new User();  
  124.         List list = em.readFromExcel("sheet1", user);  
  125.         for (int i = 0; i < list.size(); i++) {  
  126.             User newUser = (User) list.get(i);  
  127.             System.out.println(newUser.getId() + " " + newUser.getName() + " "  
  128.                     + newUser.getPassword());  
  129.         }  
  130.   
  131.     }  
  132.   


原创粉丝点击