簡體   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