栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将运行时解析的参数传递给具有多个绑定类型的方法,编译错误

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将运行时解析的参数传递给具有多个绑定类型的方法,编译错误

您需要对泛型辅助方法使用未经检查的演员表:

private static <T extends Enum<T> & Marshallable> void fooHelper(Class<? extends Marshallable> type) {    if (type.isEnum()) {        //This is safe because of the isEnum check, and we don't return any        //type with T (important because the caller can specify what T is).        @SuppressWarnings("unchecked")        final Class<T> enumType = (Class<T>)type;        final List<T> enumConstants = Arrays.asList(enumType.getEnumConstants());        foo(enumConstants);    }}

您的版本不工作的原因是因为

T extends Enum<T> & Marshallable
T
递归的约束-
这只能与类型的参数来表示。中的通配符类型参数
? extends Enum<? extends Marshallable>
不再指定该关系。

警告: 务必

fooHelper
不要返回包含的类型,
T
因为这可能导致堆污染。例如:

private static <T extends Enum<T> & Marshallable> List<T> unsafeFooHelper(Class<? extends Marshallable> type) {    if (type.isEnum()) {        //no longer safe!        @SuppressWarnings("unchecked")        final Class<T> enumType = (Class<T>)type;        return Arrays.asList(enumType.getEnumConstants());    }    return Collections.emptyList();}enum Enum1 implements Marshallable { ONE, TWO }enum Enum2 implements Marshallable { A, B }...//caller lies about what T is:List<Enum2> enumConstants = Main.<Enum2>unsafeFooHelper(Enum1.class);//sometime later...Enum2 enumConstant = enumConstants.get(0); //ClassCastException


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/507736.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号