JAVA 内省

来源:互联网 发布:淘宝秒刷销量一天千单 编辑:程序博客网 时间:2024/05/01 01:22



与反射有关的内省
     JavaBean--->特殊的Java类
     知道int getAge() 和void setAge(int age)的写法
     规则:去掉set和get前缀后 然后如果第二个字母是小的,则把第一个字母变成小的;

如果第二个字母是大写,保持原样;总之,一个类被当做javaBean使用时,JavaBean

的属性是根据方法名推断出来的,它根本看 不到java类内部的成员变量;

     一个符合JavaBean的特点的类当做普通类一样进行使用,但把它当做JavaBean的

好处是:在Java EE开发中,经常用到JavaBean,很多环境要求按JavaBean方式进行操

作,受到要求的限制;JDK提供了对JavaBean操作的API,这套API叫做内省。如果自己

去通过getX方法访问私有的X有难度,用这套API操作JavaBean比用普通类的方式更方便
JavaBean的属性石根据其中的setter和getter方法来确定的,而不是根据其中的成
员变量。

main函数中

Child beanClass = new Child(3, 6);String propertyName = "m";Object v = getProperties(beanClass, propertyName);System.out.println(v);Object o = 6;setProperties(beanClass, propertyName, o);System.out.println(beanClass.getM());

独立方法

private static void setProperties(Child beanClass, String propertyName,Object o) throws IntrospectionException, IllegalAccessException,InvocationTargetException {PropertyDescriptor pd2 = new PropertyDescriptor(propertyName, beanClass.getClass());Method m = pd2.getWriteMethod();m.invoke(beanClass, o);}

private static Object getProperties(Child beanClass, String propertyName)throws IntrospectionException, IllegalAccessException,InvocationTargetException {PropertyDescriptor pd1 = new PropertyDescriptor(propertyName, beanClass.getClass());Method rm = pd1.getReadMethod();Object v = rm.invoke(beanClass);return v;}


使用BeanUtils工具包实现

BeanUtils.setProperty(beanClass, "m", 222);System.out.println(BeanUtils.getProperty(beanClass, "m").getClass().getName());PropertyUtils.setProperty(beanClass, "m", 33);System.out.println(PropertyUtils.getProperty(beanClass, "m").getClass().getName());//PropertyUtils通过get方法返回的class类型是Integer类型,而PropertyUtils通过get方法返回的class类型是String