java内省机制

内省是 Java 语言对 Bean 类属性、事件的一种处理方法(也就是说给定一个javabean对象,我们就可以得到/调用它的所有的get/set方法)。例如类 A 中有属性 name, 那我们可以通过 getName,setName 来得到其值或者设置新的值。通过 getName/setName 来访问 name 属性,这就是默认的规则。 Java 中提供了一套 API 用来访问某个属性的 getter/setter 方法,通过这些 API 可以使你不需要了解这个规则,这些 API 存放于包 java.beans 中。
    一般的做法是通过类 Introspector 来获取某个对象的 BeanInfo 信息,然后通过 BeanInfo 来获取属性的描述器( PropertyDescriptor ),通过这个属性描述器就可以获取某个属性对应的 getter/setter 方法,然后我们就可以通过反射机制来调用这些方法。下面我们来看一个例子,这个例子把某个对象的所有属性名称和值都打印出来:
//定义一个javabean
public class PersonBean {
   public String name;
   public String[] childname;
   public String[] getChildname() {
      return childname;
   }
   public void setChildname(String[] childname) {
      this.childname = childname;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}
定义一个测试类,来进行一下set和get方法的调用举例
 
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
public class TestIntrospector {
   public static void main(String[] args) throws IllegalArgumentException,
                           IllegalAccessException, SecurityException, NoSuchMethodException,
                           InvocationTargetException, IntrospectionException {
  //演示一下get方法的调用
      //初始化一个javabean对象
      PersonBean pb=new PersonBean();
      pb.setName("kangjian");
      String[] childs=new String[]{"kk","jj","nn"};
      pb.setChildname(childs);
      //将该javabean中的属性放入到BeanInfo中。第二个参数为截止参数,表示截止到此类之前,
       不包括此类。如果不设置的话,那么将会得到本类以及其所有父类的info。
      BeanInfo bi=Introspector.getBeanInfo(pb.getClass(), Object.class);
      //将每个属性的信息封装到一个PropertyDescriptor形成一个数组
        其中包括属性名字,读写方法,属性的类型等等
      PropertyDescriptor[] pd=bi.getPropertyDescriptors();
      //演示如何get
      for (int i = 0; i < pd.length; i++) {
         if(pd[i].getPropertyType().isArray())  //getPropertyType得到属性类型。
         {
            //getReadMethod()得到此属性的get方法----Method对象,然后用invoke调用这个方法
            String[] result=(String[]) pd[i].getReadMethod().invoke(pb, null);
            System.out.println(pd[i].getName()+":");//getName得到属性名字
            for (int j = 0; j < result.length; j++) {
               System.out.println(result[j]);
            }
         }
         else
         {
            System.out.println(pd[i].getName()+":"+pd[i].getReadMethod().invoke(pb, null));
         }
      }
  //演示一下set方法的调用
      //初始化一个尚未set的javabean
      PersonBean pb0=new PersonBean();
      //模拟一个数据(数据名字和javabean的属性名一致)
      String name="luonan";
      String[] childname=new String[]{"luo","nan"};
 
      BeanInfo bi0=Introspector.getBeanInfo(pb0.getClass(), Object.class);
      PropertyDescriptor[] pd0=bi0.getPropertyDescriptors();
 
      for (int i = 0; i < pd0.length; i++) {
         if(pd0[i].getPropertyType().isArray())
         {
            if(pd0[i].getName().equals("childname"));
            {
               if(pd0[i].getPropertyType().getComponentType().equals(String.class))
               {//getComponentType()可以得到数组类型的元素类型
                  //getWriteMethod()得到此属性的set方法---Method对象,然后用invoke调用这个方法
                  pd0[i].getWriteMethod().invoke(pb0,new Object[]{childname});
               }
            }
         }
         else
         {
            if(pd0[i].getName().equals("name"));
            {
               pd0[i].getWriteMethod().invoke(pb0,name);
            }
         }
      }
 
      System.out.println(pb0.getName());
      String[] array=pb0.getChildname();
      for (int i = 0; i < array.length; i++) {
         System.out.println(array[i]);
      }
   }
} 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值