内省操作JavaBean

来源:互联网 发布:德州扑克算法 编辑:程序博客网 时间:2024/06/06 08:23

为了让程序员们更好的操作Java对象的属性,SUN公司开发了一套API,被业界内称为:内省;内省的出现有利于了对类对象属性的操作,减少了代码的数量。

内省访问JavaBean有两种方法:

       一、通过PropertyDescriptor来操作Bean对象

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

一、PropertyDescriptor类

javabean
public class Person {private String name;public String age;public String getAge() {return age;}public void setAge(String age) {this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Person() {super();}public Person(String name, String age) {super();this.name = name;this.age = age;}
操作javabean
public static void main(String[] args) throws Exception {Person p = new Person("zhangsan","123");//name是Person类中属性String propertyName="name";//此时想要操作的是Person类中的name属性PropertyDescriptor pd = new PropertyDescriptor(propertyName, p.getClass());//根据名字得到属性的get方法Method merhodGetName = pd.getReadMethod();//执行Person类的get方法Object retVal= merhodGetName.invoke(p);System.out.println("retVal "+retVal);//得到Person类的set方法,我原本以为此时得到的应该是age的set方法,但是经验证此处操作的依然是name属性//Method methodSetAge = pd.getWriteMethod();PropertyDescriptor pd2 = new PropertyDescriptor("age",p.getClass());//此时pd2操作的就是age属性Method methodSetAge = pd2.getWriteMethod();//为对象p的age属性赋值100methodSetAge.invoke(p, "100");//得到age的get方法Method methodGetAge = pd2.getReadMethod();//执行age的get方法Object retVal2 = methodGetAge.invoke(p);System.out.println("retVal2 "+retVal2);System.out.println(p.getAge());}

输出
retVal zhangsan
retVal2 100
100

二、Introspector类

同样的javabean

操作javabean
public static void main(String[] args) throws Exception {Person p = new Person();// 通过Introspector来获取bean对象的beaninfo// BeanInfo bif = Introspector.getBeanInfo(Person.class);BeanInfo bif = Introspector.getBeanInfo(p.getClass());// 通过beaninfo来获得属性描述器(propertyDescriptor)PropertyDescriptor pds[] = bif.getPropertyDescriptors();// 通过属性描述器来获得对应的get/set方法for (PropertyDescriptor pd : pds) {// 获得并输出字段的名字System.out.println("pg.getname  " + pd.getName());// 获得并输出字段的类型System.out.println(pd.getPropertyType());if (pd.getName().equals("name")) {// 获得PropertyDescriptor对象的写方法Method md = pd.getWriteMethod();// 执行写方法md.invoke(p, "zhangsan");}}// 输出所赋值字段的值System.out.println(p.getName());}
输出
pg.getname  age
class java.lang.String
pg.getname  class
class java.lang.Class
pg.getname  name
class java.lang.String
zhangsan

0 0
原创粉丝点击