zoukankan      html  css  js  c++  java
  • 内省(Introspector)

    1.为什么要学内省?
    开发框架时,经常需要使用Java对象的属性来封装程序的数据,每次都使用反射技术完成此类操作过于麻烦,所以sun公司开发了一套API,专门用于操作java对象的属性。

    2.什么是java对象的属性和属性的读写方法?

    内省访问JavaBean属性的两种方式:
    1)通过PropertyDescriptor类操作Bean的属性
    2)通过Introspector类获得Bean对象的BeanInfo,然后通过BeanInfo来获取属性的描述器(PropertyDescriptor),通过这个属性描述器就可以获取某个属性对应的getter/setter方法,然后通过反射机制来调用这些方法。

    3.

    代码1(Person 类):

    package cn.itcast.introspector;

    public class Person { //javabean封装用户数据
    private String name;//字段
    private String password;//字段
    private int age;//字段
    public String getAb() {//属性
    return null;
    }
    public String getName() {//属性
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public String getPassword() {
    return password;
    }
    public void setPassword(String password) {
    this.password = password;
    }
    public int getAge() {
    return age;
    }
    public void setAge(int age) {
    this.age = age;
    }

    }

    代码2(Demo1 类):

    package cn.itcast.introspector;

    import java.beans.BeanInfo;
    import java.beans.IntrospectionException;
    import java.beans.Introspector;
    import java.beans.PropertyDescriptor;
    import java.lang.reflect.Method;

    import org.junit.Test;

    //使用内省api操作bean的属性
    public class Demo1 {
    // 得到bean的所有属性
    @Test
    public void test1() throws Exception {
    BeanInfo info = Introspector.getBeanInfo(Person.class, Object.class);
    PropertyDescriptor[] pds = info.getPropertyDescriptors();
    for (PropertyDescriptor pd : pds) {
    System.out.println(pd.getName());
    }
    }

    // 操纵bean的指定属性:age
    @Test
    public void test2() throws Exception {
    Person p = new Person();
    PropertyDescriptor pd = new PropertyDescriptor("age", Person.class);

    // 得到属性的写方法,为属性赋值
    Method method = pd.getWriteMethod();
    method.invoke(p, 45);

    // 获取属性的值
    method = pd.getReadMethod();
    System.out.println(method.invoke(p, null));
    }

    // 高级点的内容:获取当前操作的属性的类型
    @Test
    public void test3() throws Exception {
    Person p = new Person();
    PropertyDescriptor pd = new PropertyDescriptor("age", Person.class);
    System.out.println(pd.getPropertyType());
    }
    }

  • 相关阅读:
    WebGIS中解决使用Lucene进行兴趣点搜索排序的两种思路
    WebGIS中兴趣点简单查询、基于Lucene分词查询的设计和实现
    手机端和网页端使用同一后台时进行会话控制的一种思路
    由项目浅谈JS中MVVM模式
    数字转换为汉字小算法
    6. GC 调优(工具篇)
    Android基础工具类重构系列一Toast
    <html>
    Android自己定义控件--圆形进度条(中间有图diao)
    jquery-ajax-php(内容点赞并进行cookie限制实现)
  • 原文地址:https://www.cnblogs.com/xiaohuihui123/p/4359136.html
Copyright © 2011-2022 走看看