IntroSpector---内省:用于对JavaBean操作。
JavaBean是一种特殊的Java类,主要用于传递数据信息,这种java类中的方法主要用于访问私有的字段,且方法名符合某种命名规则。
把一个类当做JavaBean来看,JavaBean的属性是根据getAge()和setAge(int age)方法名称推断出来的,不是根据内部成员变量推断的!eg:
- <span style="font-size:18px;">class Person{
- private int x;
- public int getAge(){
- return x;
- }
- public void setAge(int age){int age}{
- this.x=age;
- }
- }</span>
把Person当做一个JavaBean对象来看,有一个age属性。JavaBean属性特点,去掉set、和ge前缀,剩下来的属性就是JavaBean的属性名。属性命名规则:
eg: Age------>a如第二个字母小写,则把首字母变成小写--->age
方法对应的JavaBean属性:
getTime----->time setTime---->time getCUP----->CPU
JavaBean作用:
1. 在java EE开发中,经常使用JavaBean,环境要求按JavaBean操作。
2. JDK提供了对JavaBean进行操作的一些API,这套API就称为内省。用内省的API操作JavaBean比普通类的方式更方便。
补充:
可以将模块传递信息封装到JavaBean中,JavaBean的实例对象通常称之为值对象(Value Object,简称VO)。简单内省操作eg:
- class ReflectionPoint{
- private int x;
- pirvate int y;
- public ReflectionPoint(int x,int y){
- this.x = x;
- this.y = y;
- }
- public void setX(int x){
- this.x = x;
- }
- public int getX(){
- return x;
- }
- public void setY(int y){
- this.y = y;
- }
- public int getY(){
- return y;
- }
方法一:
- <span style="font-size:18px;">publicclass IntroSpectorTestone {
- publicstaticvoid main(String[] args)throws Exception {
- ReflectPoit s=new ReflectPoit(3, 5);
- String x="x";
- ObjectretValue =getProperty(s, x);
- System.out.println(retValue);
- Object obj=7;
- setProperty(s, x, obj);
- System.out.println(s.getX())
- }</span>
//思路:PropertyDescriptor---->getReadMethod------>invoke
- privatestaticObjectgetProperty(Objects, String x)
- throws IntrospectionException, IllegalAccessException,
- InvocationTargetException {
- PropertyDescriptor pd=new PropertyDescriptor(x, ReflectPoit.class);
- //PropertyDescriptor属性描述符,得到目标类的属性描述符
- Method methodGetX=pd.getReadMethod();;//得到可读的方法
- ObjectretValue=methodGetX.invoke(s); //调用相应对对象可写的方法,返回属性值
- return retValue;
- }
- private static Object getProperty(Object s, String x)
- throws IntrospectionException, IllegalAccessException, InvocationTargetException {
- PropertyDescriptor pd=newPropertyDescriptor(x, ReflectPoit.class);
- Method methodGetX=pd.getReadMethod();
- Object retValue=methodGetX.invoke(s);
- return retValue;
- }
- }
个人总结:JavaBean中通过内省的方法到相应属性的get和set方法。
技巧:代码抽取成方法:Refactor-----Extract Method
只要调用了这个方法,并给这个方法传递了一个对象、属性名和设置值,它就能完成属性修改的功能。
得到BeanInfo最好采用“obj.getClass()方式”,而不要采用“类名.class方式”这样程序更通用。
方法二:
采用遍历BeanInfo的所有属性方法来查找和设置某个RefectPoint对象的x属性。在程序中把一个类当做JavaBean来看,就是调用IntroSpector.getBeanInfo方法,得到的BeanInfo对象封装了把这个类当做JavaBean看的结果信息。核心代码:
//思路: BeanInfo---->PropertyDesciptor----->getReadMethod()---->invoke
- <span style="font-size:18px;"> BeanInfo beanInfo=Introspector.getBeanInfo(ReflectPoit.class);
- PropertyDescriptor[]pd=beanInfo.getPropertyDescriptors();
- Object retValue=null;
- for(PropertyDescriptorpt:pd){//PropertyDescriptor属性描述符
- if(pt.getName().equals(x)){
- MethodmethodGet=pt.getReadMethod();//得到可读的方法
- retValue=methodGet.invoke(s);//返回相应对象的属性值
- }
- }</span>
Java 7新特性 Mapmap={name:”xxxx”,age:121};map的定义方法
BeanUtils是以字符串进行操作,PropertyUtils是以本身的类型进行操作