判断一个类中的属性是否可写

15 篇文章 0 订阅

相关类介绍

在 Java 中,可通过 java.beans 包下的相关类,来获取一个类中属性的描述信息,常用的方法如下:

public class SimpleTest {

    public static void main(String[] args) throws IntrospectionException {
        BeanInfo beanInfo = Introspector.getBeanInfo(NameMatchMethodPointcutAdvisor.class);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        System.out.println(beanInfo.getClass().getName());

        for (PropertyDescriptor pd : propertyDescriptors) {
            System.out.println(pd.getName());
        }

        System.out.println("*************************");

        for (PropertyDescriptor pd : propertyDescriptors) {
            Method writeMethod = pd.getWriteMethod();
            Method readMethod = pd.getReadMethod();
            if (writeMethod != null) {
                System.out.println("write method: " + writeMethod.getName());
            }
            if (readMethod != null) {
                System.out.println("read method: " + readMethod.getName());
            }
        }
    }
}

执行后,发现获取的 beanInfo 类型是 java.beans.GenericBeanInfo,并且会获得相应的读写方法。

下面看看判断示例:

public static boolean isWritableProperty(Class<?> clazz, String propertyName) throws IntrospectionException {
	BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
	PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
	for (PropertyDescriptor pd : propertyDescriptors) {
		if (propertyName.equals(pd.getName()) && pd.getWriteMethod() != null) {
			return true;
		}
	}
	return false;
}

这样,就可以判断给定的属性在这个类中是否可写。

使用案例

在 spring 中,对创建的半成品对象进行属性填充时,会判断这个配置的属性在这个给定类中是否可写。

@Override
public boolean isWritableProperty(String propertyName) {
	try {
		PropertyHandler ph = getPropertyHandler(propertyName);
		if (ph != null) {
			return ph.isWritable();
		}
		else {
			// Maybe an indexed/mapped property...
			getPropertyValue(propertyName);
			return true;
		}
	}
	catch (InvalidPropertyException ex) {
		// Cannot be evaluated, so can't be writable.
	}
	return false;
}

以上代码来自 BeanWrapperImpl 的父类 AbstractNestablePropertyAccessor,核心判断就是前面的判断示例所实现的那样。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潭影空人心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值