假设我知道一个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());
}