获取JavaBean实体类的读写get/set方法

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 通过 get/set 来对属性进行操作,主要是因为当字段名更改,字段读写方式(过程)更改了,能向后兼容;如果使用Object.field的方式不便于维护。

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


版权声明:本文为howeres原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。