java反射机制获取对象属性

项目场景:

今天做一个工资表的导出,表格每一列的内容想用反射工资表的对象遍历出每一列的值

问题描述:

在执行时报错:java.lang.IllegalAccessException: Class com.test.demo.test.TestField can not access a member of class com.test.demo.domain.Stu1 with modifiers "private"
	//设置内容
	if(wageList!=null && wageList.size()>0){
		for(int i=0;i<wageList.size();i++){
			TeeWage teeWage = wageList.get(i);
			HSSFRow tRow = sheet.createRow(i + 1); //添加行
			
			//添加序号
			HSSFCell numCell = tRow.createCell(0);
			numCell.setCellValue(i + 1);
			numCell.setCellStyle(style1);
			
			Field[] declaredFields = teeWage.getClass().getDeclaredFields();
			//遍历添加序号信息
			for (int j = 1; j < declaredFields.length; j++){
					Field f = declaredFields[j];
					HSSFCell cell8 = tRow.createCell(j);
					cell8.setCellValue(f.get(teeWage)+"");
					cell8.setCellStyle(style1);
			}
		}
	}

原因分析:

由于实体类变量都是private修饰的,所以在 f.get(obj) 需要 f.setAccessible(true);

关于 setAccessible() : 不管成员变量的访问权限是public、protected、默认、还是private,isAccessible()方法都返回false. 但是访问(f.get(obj))private修饰的成员变量,需要setAccessible(true),否则抛出IllegalAccessException,而其他访问权限修饰的成员变量可以直接访问。

解决方案:

添加 f.setAccessible(true);
	//设置内容
	if(wageList!=null && wageList.size()>0){
		for(int i=0;i<wageList.size();i++){
			TeeWage teeWage = wageList.get(i);
			HSSFRow tRow = sheet.createRow(i + 1); //添加行
			
			//添加序号
			HSSFCell numCell = tRow.createCell(0);
			numCell.setCellValue(i + 1);
			numCell.setCellStyle(style1);
			
			Field[] declaredFields = teeWage.getClass().getDeclaredFields();
			//遍历添加序号信息
			for (int j = 1; j < declaredFields.length; j++){
					Field f = declaredFields[j];
					//开启可读权限
					f.setAccessible(true);
					HSSFCell cell8 = tRow.createCell(j);
					cell8.setCellValue(f.get(teeWage)+"");
					cell8.setCellStyle(style1);
			}
		}
	}

测试Demo:

有些东西好久不去用就会忘,在此写一个Demo复习一下:

实体类

public class Stu1 {
    private String name;
    private Integer id;
    private boolean gender;// true:男;false:女
    private Date birthday;
    private int score;

    public Stu1() {
    }

    public Stu1(Integer id, String name, int score, Date birthday, boolean gender) {
        super();
        this.id = id;
        this.name = name;
        this.score = score;
        this.birthday = birthday;
        this.gender = gender;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public boolean isGender() {
        return gender;
    }

    public void setGender(boolean gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", score=" + score + ", birthday=" + birthday + ", gender="
                + gender + "]";
    }
}

测试类

public class ReflectTest {

    public static void main(String[] args)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        Stu1 student = new Stu1();

        student.setBirthday(new Date());
        student.setGender(false);
        student.setId(3);
        student.setName("王五");
        student.setScore(99);

        // 通过实例得到类
        @SuppressWarnings("rawtypes")
        Class studentClass = (Class) student.getClass(); // studentClass

        /*
         * 得到类中的所有属性集合
         */
        Field[] field = studentClass.getDeclaredFields();

        for (int i = 0; i < field.length; i++) {
            Field f = field[i];
            int size = field.length;// 属性个数
            f.setAccessible(true); // 设置些属性是可以访问的

            String type = f.getType().toString();// 得到此属性的类型
            String key = f.getName();// key:得到属性名
            Object value = null;// 得到此属性的值
            value = f.get(student);

            //System.out.println("属性个数:" + size + "\t 类型:" + type + "\t 属性名:" + key + "\t 属性值 : " + value);

            if (key.endsWith("name")) {
                f.set(student, "张三");// 给属性设值
                System.out.println(student);
            } else if (key.endsWith("id")) {
                f.set(student, 6);
                System.out.println(student);
            } else if (key.endsWith("gender")) {
                f.set(student, true);
                System.out.println(student);
            } else if (key.endsWith("birthday")) {
                f.set(student, new Date());
                System.out.println(student);
            } else if (key.endsWith("score")) {
                f.set(student, 44);
                System.out.println(student);
            }
        }

        /*
         * 得到类中所有方法的集合
         */
        Method[] methods = studentClass.getMethods();
        for (int i = 0; i < methods.length; i++) {
            Method method = methods[i];
            if (method.getName().startsWith("get")) {
                System.out.print("类中的get方法:" + method.getName() + "\t");
                System.out.println("get方法的值:" + method.invoke(student));
            }
        }
    }
}
不积跬步,无以至千里;不积小流,无以成江海。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值