Java中使用内省操作Bean的所有属性

Introspector 类为通过工具学习有关受目标 Java Bean 支持的属性、事件和方法的知识提供了一个标准方法。
对于这三种信息,Introspector 将分别分析 bean 的类和超类,寻找显式或隐式信息,使用这些信息构建一个全面描述目标 bean 的 BeanInfo 对象。
内省的类结构
这里写图片描述

经常用到的关于内省的地方就是java中的框架了,根据配置信息,配置文件实例化具体的Bean类,调用getter,setter方法等

废话不多说,代码演示:

@Test
    // 得到Bean类的所有属性
    public void testGetProperties() throws IntrospectionException {
        //getBeanInfo()中的第二个参数,表示获取属性截止到(不包括)的类,
        BeanInfo info = Introspector.getBeanInfo(NamingRecard.class,
                Object.class);
        PropertyDescriptor[] pds = info.getPropertyDescriptors();
        for (PropertyDescriptor pd : pds) {
            System.out.println(pd.getName());
        }
    }

    @Test
    // 操作Bean的指定属性
    public void useProperties() throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        NamingRecard nr = new NamingRecard();
        PropertyDescriptor pd = new PropertyDescriptor("className",
                NamingRecard.class);
        //获取属性的写方法,为属性赋值
        Method method=pd.getWriteMethod();
        //获取属性值的类型
        Class clazz=pd.getPropertyType();
        method.invoke(pd, "计科131");
        //传统的方法
        System.out.println(nr.getClassName());
        //获取属性的值
        method=pd.getReadMethod();
        System.out.println(method.invoke(nr, null));
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值