![](/img/trans.png)
[英]How to “dynamically” cast an instance of Object type into its specific data type?
[英]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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.