日期:2014-05-18  浏览次数:20913 次

请高手进来看看
看了jdk还是不明白PropertyDescriptor在什么情况用instanceof对较 IndexedPropertyDescriptor类为true
请高手们讲解一下

------解决方案--------------------
descriptors=beanInfo.getPropertyDescriptors(); //这里返回的是PropertyDescriptor数组

if(descriptors[i] instanceof IndexedPropertyDescriptor) //这里为什么判断不相等 请高手讲一下 

ndexedPropertyDescriptor descriptor = (IndexedPropertyDescriptor)descriptors[i]; //这里需要进行强制转换


IndexedPropertyDescriptor是PropertyDescriptor的子类,一个对象是PropertyDescriptor的实例,但未必就一定是IndexedPropertyDescriptor的实例,反过来,一个对象是IndexedPropertyDescriptor的实例,就一定是PropertyDescriptor的实例。从代码上看,是要将descriptors数组的每个PropertyDescriptor对象进行强制转换,转换为IndexedPropertyDescriptor对象,如果不作判断,当某个PropertyDescriptor对象不是IndexedPropertyDescriptor的实例时就会出错,所以转换前进行类型判断。
不知道这样说LZ明不明白?


------解决方案--------------------
接口A有两个实现类B和C:

B b = new B();
C c = new C();

b instanceof A : true
c instanceof A : true

b instanceof C : false 楼主问题的情况即是如此
c instanceof B : false 楼主问题的情况即是如此