内省操作JavaBean

来源:互联网 发布:股票日内交易软件 编辑:程序博客网 时间:2024/05/29 19:19
//使用内省操作bean
public class Test01 {
  public static void main(String[] args) throws Exception {
      //test1();
      test2();
}
   private  static void test1() throws IntrospectionException{
       //得到bean的属性
       BeanInfo info=Introspector.getBeanInfo(Person.class,Object.class);
       PropertyDescriptor[]pds=info.getPropertyDescriptors();
       for(PropertyDescriptor pd:pds){
           System.out.println(pd.getName());
       }
   }
   private  static void test2() throws Exception {
       //操作bean的属性
        Person person=new Person();
        PropertyDescriptor pds=new PropertyDescriptor("name",Person.class);
        //得到属性的set方法,为属性赋值
        Method method=pds.getWriteMethod();
        method.invoke(person, "张三");
        //得到属性的get方法
        Method m=pds.getReadMethod();
       System.out.println(m.invoke(person, null));
        //获得属性的类型
        System.out.println(pds.getPropertyType());
      
   }
}

0 0
原创粉丝点击