[英]Java Generics- Can I create a list dynamically based on variable type
有沒有什么方法可以在運行時創建泛型類型的特定實例?
例如。
Cacheable instance = getCacheable(someInput);
getCacheble方法將返回Cacheable的實例。 所以它可以是實現Cacheable的任何類。例如Customer,Product等。現在我想創建一個由getCacheable返回的特定類型的列表,如下所示。這可能嗎? 如果是的話怎么做?
List<? extends Cacheable> cacheList = new ArrayList<>();
我想基於getCacheable方法返回的實例創建ArrayList<Product> or ArrayList<Customer>
。
你可以這樣做:
Cacheable instance = getCacheable(someInput);
List<? extends Cacheable> l = new ArrayList<>();
l = Collections.checkedList(l, instance.getClass());
由於類型擦除,編譯時可訪問的所有信息在運行時都會丟失。 checkedList
方法將確保您的列表只接收instance
變量類的instance
。
更新:你也可以這樣做:
public static <T extends Cacheable> MyOwnCustomGeneric<T> createMyOwnCustomGeneric(Class<T> type) {
return new MyOwnCustomGeneric<T>();
}
// ...
IMyOwnCustomGeneric foo = createMyOwnCustomGeneric(instance.getClass());
使用通用幫助函數:
public static <T extends Cacheable>ArrayList<T> createList(Class<T> claz)
{
return new ArrayList<>();
}
ArrayList<? extends Cacheable>alist = createList(instance.getClass());
if (instance instanceof Product) {
// create ArrayList<Product>;
} else {
// create ArrayList<Customer>;
}
但這並不是一般的和動態的。
唯一的方法是打開instance
的類型,但是你可以用它做的事情不多:
List<? extends Cacheable> cacheList = null;
if (instance instanceof Product)
cacheList = new ArrayList<Product>();
// etc
但你對這份清單怎么辦? 你不能添加任何東西。 也許您在創建項目時會向其添加項目,但這可能不是用例,因為它是一個緩存列表。
如果您以后需要向其中添加項目,請參閱此答案是正確的方法。
如果您以后不再添加項目,那么類型是List<Cacheable>
還是List<? extends Cacheable>
無關緊要List<? extends Cacheable>
List<? extends Cacheable>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.