繁体   English   中英

如何将泛型类型的类对象强制转换为该类型的特定实例

[英]How to Cast the Class Object of a Generic Type to a Specific Instance of that Type

我有一个通用接口,我们称之为GenericInterface<T> 我需要将该接口的类对象传递给期望(通过另一个类型参数指定)该类型的特定实例的方法。 假设我想调用java.util.Collections.checkedList()

List<GenericInterface<Integer>> list = Collections.checkedList(
    new ArrayList<GenericInterface<Integer>>(),
    GenericInterface.class);

这不起作用,因为Class<GenericInterface>不能隐式转换为Class<GenericInterface<Integer>> ,最安全的方法是什么? 我能想到的最好的是:

List<GenericInterface<Integer>> list = Collections.checkedList(
    new ArrayList<GenericInterface<Integer>>(),
    (Class<GenericInterface<Integer>>) (Class<?>) GenericInterface.class);

它的工作原理,但改变列表的类型不会保护我如List<SomeOtherInterface>不也更换类对象参数SomeOtherInterface.class

有类似的问题:

简短的回答是,无法在 Java 中找出泛型类型参数的运行时类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM