标签:ann catch cto ash illegal access element nullable support
反射对bean的collection属性赋值对collection使用反射创建时会遇到不知道具体实现类型而烦恼
比如:
class School{
private List classes ; //班级列表
public void setClasses(List classes){
this.classes=classes;
}
pulbic List getClasses(){
return this classes;
}
}
Class<?> schoolClazz=Class.forName(School.class.getTypeName());
schoolClazz.getMethod("setClasses",argsClass);
//这里argsClass应该是具体的实现类 很明确这里是需要Arraylist 但是如果是这样代码
class School{
private Collection classes ; //班级列表
public void setClasses(Collection classes){
this.classes=classes;
}
pulbic Collection getClasses(){
return this classes;
}
}
//惨了 不知道实现类是什么了 应该是ArrayList.class 还是 HashSet.class ?
没办法了?
参考下spring里面的代码:
public static <E> Collection<E> createCollection(Class<?> collectionType, @Nullable Class<?> elementType, int capacity) {
Assert.notNull(collectionType, "Collection type must not be null");
if (collectionType.isInterface()) {
if (Set.class == collectionType || Collection.class == collectionType) {
return new LinkedHashSet<>(capacity);
}
else if (List.class == collectionType) {
return new ArrayList<>(capacity);
}
else if (SortedSet.class == collectionType || NavigableSet.class == collectionType) {
return new TreeSet<>();
}
else {
throw new IllegalArgumentException("Unsupported Collection interface: " + collectionType.getName());
}
}
else if (EnumSet.class == collectionType) {
Assert.notNull(elementType, "Cannot create EnumSet for unknown element type");
// Cast is necessary for compilation in Eclipse 4.4.1.
return (Collection<E>) EnumSet.noneOf(asEnumType(elementType));
}
else {
if (!Collection.class.isAssignableFrom(collectionType)) {
throw new IllegalArgumentException("Unsupported Collection type: " + collectionType.getName());
}
try {
return (Collection<E>) ReflectionUtils.accessibleConstructor(collectionType).newInstance();
}
catch (Throwable ex) {
throw new IllegalArgumentException(
"Could not instantiate Collection type: " + collectionType.getName(), ex);
}
}
}
这里返回了具体的实现类 直接使用它的返回的具体实现类
标签:ann catch cto ash illegal access element nullable support
原文地址:http://blog.51cto.com/5013162/2142091