這個問題似乎很尷尬,但我們在檢索javabean的PropertyDescriptors時遇到了一個奇怪的行爲。 下面是1.6,1.7和1.8的一個簡單的代碼執行結果,編譯1.6符合。JRE 1.8仍然遵循關於IndexedPropertyDescriptor的JavaBean規範嗎?
Java 1.6的執行:
[email protected] < - 不重要 [email protected] < - 是的,我有一個索引屬性
的Java 1.7執行:
java.beans.PropertyDescriptor [name = class; propertyType = class java.lang.Class; readMethod = public final native java.lang.Class java.lang.Object.getClass()] < - 不重要 java.beans.IndexedPropertyDescriptor [name = values; indexedPropertyType = class java.lang.String; indexedReadMethod =公共java.lang.String中JavaBean.getValues(INT)] < - 是的,我有一個索引屬性
的Java 1.8執行:
java.beans.PropertyDescriptor中的[名稱= A類; propertyType = class java.lang.Class; readMethod = public final native java.lang.Class java.lang.Object.getClass()] < - 不重要 java.beans.PropertyDescriptor [name = values; propertyType = interface java.util.List; readMethod = public java.util.List JavaBean.getValues()] < - Ouch!這不再是索引的屬性!
它爲什麼改變了?
javabean規範說明了如何使用索引訪問屬性。它不是強制性的使用數組作爲索引屬性的容器。我錯了嗎?
我閱讀規範和章節8.3.3談論索引屬性的設計模式,而不是嚴格的規則。
如何在不重構所有應用程序的情況下使以前的行爲再次迴歸? <舊的應用程序,大量的代碼修改,等等
感謝您的答案,
JavaBean類
import java.util.ArrayList;
import java.util.List;
public class JavaBean {
private List<String> values = new ArrayList<String>();
public String getValues(int index) {
return this.values.get(index);
}
public List<String> getValues() {
return this.values;
}
}
主要類
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
public class Test {
public static void main(String[] args) throws IntrospectionException {
PropertyDescriptor[] descs =
Introspector.getBeanInfo(JavaBean.class).getPropertyDescriptors();
for (PropertyDescriptor pd : descs) {
System.out.println(pd);
}
}
}
那麼......我預計這種答案。我仍然不明白爲什麼這種行爲會以這種方式發生變化,而不是更嚴格的實施。無論如何,這是個很好的答案謝謝。因爲我們使用的是commons-beanutils,所以我最好通過使用BeanIntrospector來擴展這個API的功能,這個BeanIntrospector可以在自我定義的同時檢測一個IndexedProperty,同時反省一個bean。 –