[反射] 获取JavaBean实体类的读写 getter / setter 方法

简介

主要是两个类 IntrospectorPropertyDescriptor

BeanInfo beanInfo = Introspector.getBeanInfo(vo.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors() // 只有这个方法
// or
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fieldName, vo.getClass());

// 最终都是
Method readMethod = propertyDescriptor.getReadMethod();
Method writeMethod = propertyDescriptor.getWriteMethod();
writeMethod.invoke(vo,"hahah");
System.out.println(readMethod.invoke(vo));

详细示例

public void information(SomethingVO vo) {
		// 方式1
		BeanInfo beanInfo = Introspector.getBeanInfo(vo.getClass());
		for(PropertyDescriptor property: beanInfo.getPropertyDescriptors()){
			Method getMethod = property.getReadMethod(); // 获得get方法
			getMethod.invoke(vo);  // 执行方法
			Method setMethod = property.getWriteMethod(); // 获得set方法
			setMethod.invoke(vo,"各个参数"); // 执行set方法, 后面带参数
		}
		// 方式2
        Field[] declaredFields = vo.getClass().getDeclaredFields();
        for (Field field:declaredFields){
			PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), vo.getClass());
			Method getMethod = propertyDescriptor.getReadMethod(); // 获得get方法
			getMethod.invoke(vo);  // 执行方法
			Method setMethod = propertyDescriptor.getWriteMethod(); // 获得set方法
			setMethod.invoke(vo,"各个参数"); // 执行set方法, 后面带参数
		}
		// 方式2,可以单独获取某一个字段,比如name字段
		PropertyDescriptor name = new PropertyDescriptor("name", vo.getClass());
		Method readMethod = name.getReadMethod();
		Method writeMethod = name.getWriteMethod();
		writeMethod.invoke(vo,"hahah");
		System.out.println(readMethod.invoke(vo));
}

设置 JavaBean 通过 getter / setter 来对属性进行操作,主要是因为当字段名更改,字段读写方式(过程)更改了,能向后兼容;如果使用Object.field的方式不便于维护。

注意⚠️:对应实体类必须遵循Bean原则,如果set方法返回的this对象而不是void,执行时就会抛出异常java.beans.IntrospectionException: Method not found: setName

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值