[英]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.