瞌睡中的葡萄虎

博客园 首页 新随笔 联系 订阅 管理
  148 随笔 :: 0 文章 :: 16 评论 :: 40万 阅读

访问JavaBean属性的两种方式

1)直接调用bean的setXXX或getXXX方法;

2)通过内省技术访问(java.beans包提供了内省的API),内省技术访问也提供了两种方式:

  a)通过PropertyDescriptor类操作Bean的属性;

  b)通过Introspector类获得Bean对象的 BeanInfo,然后通过 BeanInfo 来获取属性的描述器( PropertyDescriptor ),通过这个属性描述器就可以获取某个属性对应的 getter/setter 方法,然后通过反射机制来调用这些方法。

复制代码
public class Person {
    private String name; // 字段
    private String password;// 字段
    private Integer age;// 字段
    // 对字段添加了get或者set方法了,才叫做属性
    public String getXxx() {
        return "aa";
    }
    setter/getter
}
复制代码

以下通过内省机制来操作Person对象。

 

获得类所有的属性

复制代码
@Test
    public void test1() throws Exception {

        BeanInfo beanInfo = Introspector.getBeanInfo(Person.class);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); //得到属性描述符

        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            System.out.println(propertyDescriptor.getName());
        }
    }
复制代码

执行结果:age  class  money  name  password  xxx

包括了从父类中继承过来的属性class

 

获得本类中的所有属性

复制代码
@Test
    public void test2() throws Exception {
        // 剔除Object继承过来的属性
        BeanInfo beanInfo = Introspector.getBeanInfo(Person.class, Object.class);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            System.out.println(propertyDescriptor.getName());
        }
    }
复制代码

 

操纵bean的指定属性

复制代码
@Test
    public void test3() throws Exception {
        Person person = new Person();

        PropertyDescriptor propertyDescriptor = new PropertyDescriptor("age", Person.class);

        // 得到属性的写方法,为属性赋值
        Method setAgeMethod = propertyDescriptor.getWriteMethod(); // setAge
        setAgeMethod.invoke(person, 34);

        // 获取属性的值
        System.out.println(person.getAge());
        Method getAgeMethod = propertyDescriptor.getReadMethod();
        System.out.println(getAgeMethod.invoke(person, null));
    }
复制代码

 

获取当前操作的属性的类型

@Test
    public void test4() throws Exception {
        PropertyDescriptor propertyDescriptor = new PropertyDescriptor("money",Person.class);
        
        Class<?> propertyType = propertyDescriptor.getPropertyType();
        System.out.println(propertyType);
    }

 

posted on   瞌睡中的葡萄虎  阅读(464)  评论(0编辑  收藏  举报
编辑推荐:
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
阅读排行:
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· 一个基于 .NET 开源免费的异地组网和内网穿透工具
· 《HelloGitHub》第 108 期
· Windows桌面应用自动更新解决方案SharpUpdater5发布
· 我的家庭实验室服务器集群硬件清单
点击右上角即可分享
微信分享提示