假设我有一个List<Base>
,我知道它只包含Derived
类型的元素,我如何强制转换为List<Derived>
?
我的解决方案:
public static <T> List<T>
cast(List<? super T> list, Class<T> clazz) {
if( list.stream().allMatch( clazz::isInstance ) )
return (List<T>) list;
else
throw new IllegalArgumentException ("Not all inputs are of class " + clazz.getName());
}
public static void main(String[] args) {
List<Number> foo = new ArrayList<>();
List<Integer> a = cast(foo);
System.out.println("a = " + a);
}
public static <T, C extends T> List<C> cast( List<T> l ) {
return (List<C>) l;
}