二级java辅导:内省机制
来源:优易学  2011-9-29 14:46:59   【优易学:中国教育考试门户网】   资料下载   IT书店

 

 */

  BeanInfo beanInfo = Introspector.getBeanInfo(sb.getClass());

  //将每个属性的信息封装到一个PropertyDescriptor形成一个数组其中包括属性名字,读写方法,属性的类型等等 PropertyDescriptor[] propertys = beanInfo.getPropertyDescriptors();

  for(PropertyDescriptor property : propertys) {

  System.out.println("属性名:" + property.getName()); System.out.println("类型:" + property.getPropertyType());

  }

  System.out.println();

  System.out.println("列出SimpleBean的所有方法"); MethodDescriptor[] methods = beanInfo.getMethodDescriptors();

  for(MethodDescriptor method : methods) {

  System.out.println(method.getName());

  }

  System.out.println();

  /**

  *重新设置属性值

  */

  for(PropertyDescriptor property : propertys) {

  if(property.getPropertyType().isArray()){  //getPropertyType得到属性类型。

  if(property.getPropertyType().isArray()) { if("hobby".equals(property.getName())) {

  //getComponentType()可以得到数组类型的元素类型

  if(property.getPropertyType().getComponentType().equals(String.class)) { //getWriteMethod()得到此属性的set方法----Method对象,然后用invoke调用这个方法 property.getWriteMethod().invoke(sb, new Object[]{new String[]{"tennis","fishing"}});

  }

  }

  }

  } else if("name".equals(property.getName())) { property.getWriteMethod().invoke(sb, new Object[] { "royzhou1985" });

  }

  }

  /**

  *获取对象的属性值

  */

  System.out.println("获取对象的属性值");

  for(PropertyDescriptor property : propertys) {

  if(property.getPropertyType().isArray()){  //getPropertyType得到属性类型。

 //getReadMethod()得到此属性的get方法----Method对象,然后用invoke调用这个方法String[] result=(String[]) property.getReadMethod().invoke(sb, new Object[]{}); System.out.print(property.getName()+":");//getName得到属性名字for (int j = 0; j < result.length; j++) { System.out.print(result[j] + ",");

  }

  System.out.println();

  }

  else{

  System.out.println(property.getName()+":"+property.getReadMethod().invoke(sb, new Object[]{}));

  }

  }

  }

  }

  输出结果:

  com.royzhou.bean.SimpleBean@757aef

  name:=royzhou

  hobby:football,backetball,

  属性名:class

  类型:class java.lang.Class

  属性名:hobby

  类型:class [Ljava.lang.String;

  属性名:name

  类型:class java.lang.String

  列出SimpleBean的所有方法

  hashCode

  setHobby

  equals

  wait

  wait

  notify

  getClass

  toString

  notifyAll

  getHobby

  setName

  wait

  getName

  获取对象的属性值

  class:class com.royzhou.bean.SimpleBean hobby:tennis,fishing,

  name:royzhou1985

上一页  [1] [2] 

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训