commons-beanutils.jar可以操作使得map数据集合注入bean类对象中。
但是对于list集合数据的注入缺乏自动性
将map数据注入bean我得先new 出这个bean,然后bean.setList(new List(){{
add(new T());
add(new T());
add(new T());
}})
也就意味着我必须初始化出bean属性list,并指定这个list对象的size。缺乏自动性
改进: 修改PropertyUtilsBean.java
Object value = invokeMethod(readMethod, bean, EMPTY_OBJECT_ARRAY);
Type returnType = readMethod.getGenericReturnType();
if(value==null) {//构造一个出来 ,暂时只支持list
if(returnType.toString().contains("java.util.List"))
value = new ArrayList();
//将对象引用写回原对象
final Method writeMethod = getWriteMethod(bean.getClass(), descriptor);
final Object[] subscript = new Object[1];
subscript[0] = value;
invokeMethod(writeMethod, bean, subscript);
}
if (!value.getClass().isArray()) {
if (!(value instanceof java.util.List)) {
throw new IllegalArgumentException("Property '" + name +
"' is not indexed on bean class '" + bean.getClass() + "'");
} else {
List list = (java.util.List) value;
Type acturalType = ((java.lang.reflect.ParameterizedType) returnType).getActualTypeArguments()[0];
while(list.size()<=index){//自行构造bean
try {
list.add(((Class)acturalType).newInstance());
} catch (InstantiationException e) {
throw new RuntimeException(e.getMessage());
}
}
//get the List's value
return ((java.util.List<?>) value).get(index);
}
}