内省

来源:互联网 发布:单片机12864程序解析 编辑:程序博客网 时间:2024/05/18 02:19

        内省(Introspector) — JavaBean

         什么是JavaBean和属性的读写方法?
         访问JavaBean属性的两种方式:
         直接调用bean的setXXX或getXXX方法。
         通过内省技术访问(java.beans包提供了内省的API),内省技术访问也提供了两种方式。
                  •通过PropertyDescriptor类操作Bean的属性
                  •通过Introspector类获得Bean对象的 BeanInfo,然后通过 BeanInfo 来获取属性的描述器( PropertyDescriptor ),通过这个属性描述器就可以获取某个属性对应的 getter/setter 方法,然后通过反射机制来调用这些方法。
package cn.itcast.introspector;public class Person {private String name;private String password;private int age;public void setAb(int a) {}public void setBa(int a) {}public String getName() {return name;}public String getPassword() {return password;}public int getAge() {return age;}public void setName(String name) {this.name = name;}public void setPassword(String password) {this.password = password;}public void setAge(int age) {this.age = age;}}

内省

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;public class Demo1 {// 得到bean所有属性@Testpublic void test1() throws Exception {BeanInfo info = Introspector.getBeanInfo(Person.class);// 去掉Object里的属性getclass()BeanInfo info2 = Introspector.getBeanInfo(Person.class, Object.class);PropertyDescriptor[] pds = info.getPropertyDescriptors();// 拿到类的属性描述器for (PropertyDescriptor pd : pds) {System.out.println(pd.getName());// ab ba age name password class}}// 操纵bean的指定属性:age@Testpublic void test2() throws Exception {Person p = new Person();PropertyDescriptor pd = new PropertyDescriptor("age", Person.class);// 得到属性的写方法,为属性赋值Method method = pd.getWriteMethod();method.invoke(p, 45);System.out.println(p.getAge());// 45// 获取属性的值method = pd.getReadMethod();System.out.println(method.invoke(p, null));// 调用的是getAge()// 该方法无参数,所有是null 输出45}// 高级内容,获取当前操作的属性的类型@Testpublic void test3() throws Exception {Person p = new Person();PropertyDescriptor pd = new PropertyDescriptor("age", Person.class);// 得到属性描述器// 得到属性的写方法,为属性赋值Method method = pd.getWriteMethod();System.out.println(pd.getPropertyType());// intmethod.invoke(p, 50);System.out.println(p.getAge());// 50// 获取属性的值method = pd.getReadMethod();System.out.println(method.invoke(p, null));// 50}}


0 0
原创粉丝点击