java反射案例实战

本次主要场景为:excel导出功能,当对象Person有五个字段,依次为name,age,mobile,idCard,sex,
但是导出的Excel功能中,按照顺序导出name,mobile,sex等三个字段数据
解决方案:根据导出字段利用java反射机制获取到值
代码方案:
String[] columnNames = { "姓名" , "手机号码", "性别" };
String [] columns = { "name" , "mobile","sex" };
String fileName = "会员报表" ;
大致代码:
for ( int i = 0 ; i < columns. length ; i++) {
   fieldName = columns[i];
  getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
  tCls = t.getClass();
  getMethod = tCls.getMethod(getMethodName, new Class[] {});
  value = getMethod.invoke(t, new Object[] {});    //根据字段利用反射获取到值
}

实战如下:
public class Person {

    /** 姓名 **/
    private String name;
    /** 年龄 **/
    private Integer age;
    /** 手机号码 **/
    private String mobile;
    /** 身份证 **/
    private String idCard;
    /** 性别 **/
    private Integer sex;
  //提供get和set方法  
}
public static void main(String[] args) {
    Person person = new Person();
    person.setName("张三");
    person.setAge(18);
    person.setMobile("18888888888");
    person.setIdCard("11111");
    person.setSex(1);
    //根据反射
    String [] columns = {"name","mobile","sex"};
    for(int i=0;i<columns.length;i++){
        String fieldName = columns[i];
        String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
        try {
            Class tCls = person.getClass();
            Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
            Object value = getMethod.invoke(person, new Object[] {});
            System.out.println(value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
结果如下:
张三
18888888888
1






猜你喜欢

转载自blog.csdn.net/qq_39291929/article/details/80693711
今日推荐