如何根据注解动态调用set方法?
我想实现,excel表格动态注入到List中
这是表格数据和Emp类
现在已经可以让,表格的头和Emp类的注解的进行关联
但是我不知道如何实现动态的调用emp对象的set方法
即使不调用set方法,直接通过属性注入也行
但是我不知道怎么写了
public class Demo0<T> {
public static void main(String[] args) throws Exception {
List<Emp> emps = new ArrayList<>();
//excel表
Workbook wb = new XSSFWorkbook("d:/员工.xlsx");
int sheetLength = wb.getNumberOfSheets();
//遍历sheet
for (int i = 0; i < sheetLength; i++) {
Sheet sheet = wb.getSheetAt(i);
int rowLength = sheet.getPhysicalNumberOfRows();
//遍历行
for (int j = 0; j < rowLength; j++) {
Emp emp = new Emp();
Row row = sheet.getRow(j);
int cellLength = row.getPhysicalNumberOfCells();
//遍历列
for (int k = 0; k < cellLength; k++) {
Cell cell = row.getCell(k);
String cellValue = cell.getStringCellValue();
System.out.print(cellValue+"\t");
/*----------开始自动关联了-----------*/
//获取当前sheet的第一行,也就是excel的表头
Row title = sheet.getRow(0);
//获取当前列的表头的值
Cell titleCell = title.getCell(k);
String titleCellValue = titleCell.getStringCellValue();
//如何自动映射?
//获取Emp类的属性
Field[] fields = Emp.class.getDeclaredFields();
for (int l = 0; l < fields.length; l++) {
Field field = fields[l];
//根据属性,获取Excel注解
ExcelField ef = field.getDeclaredAnnotation(ExcelField.class);
//获取注解的值
String anTitle = ef.title();
//注解的值和excel标题的值相同的时候
//就把excel中当前列的值,注入到emp对象对应的属性中
/*******重点*****/
/*******如何根据注解,动态调用set方法?*****/
if(titleCellValue.equals(anTitle)){
emp.setEmpId(cellValue);
continue;
}
if(titleCellValue.equals(anTitle)){
emp.setEname(cellValue);
continue;
}
}
}
emps.add(emp);
System.out.println();
}
}
System.out.println(emps);
}
}
public class Emp {
@ExcelField(title = "员工姓名")
public String ename;
@ExcelField(title = "员工编号")
public String empId;
public Emp() {
}
public Emp(String empId, String ename) {
this.empId = empId;
this.ename = ename;
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
@Override
public String toString() {
return "Emp [ename=" + ename + ", empId=" + empId + "]";
}
}
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelField {
String title();
}