簡體   English   中英

實例化其構造函數帶有類對象參數的java泛型類

[英]Instanize java generic class whose constructor takes class object argument

我有SuperQueue類

public class SuperQueue<E> implements Queue<E>{

SuperQueue(Class<? extends Queue<E>> subqClass) {}

}

如何創建SuperQueue對象? 我努力了:

SuperQueue<Integer> superq = new SuperQueue<Integer> (ConcurrentLinkedQueue.class)

SuperQueue<Integer> superq = new SuperQueue<Integer> (ConcurrentLinkedQueue<Integer>.class)

在你的代碼中

SuperQueue<Integer> superq = new SuperQueue<Integer>(ConcurrentLinkedQueue.class);

您傳遞不兼容的類型,因為Class<ConcurrentLinkedQueue>無法轉換為Class<? extends Queue<Integer> Class<? extends Queue<Integer>

為了創建對象,您需要傳遞一個實現Queue<Integer>的類,例如

class Foo implements Queue<Integer> {...}

然后你可以像這樣使用它

SuperQueue<Integer> superq = new SuperQueue<Integer>(Foo.class);
SuperQueue<Integer> superq =
    new SuperQueue<Integer>((Class<ConcurrentLinkedQueue<Integer>>)
                            (Class<?>)ConcurrentLinkedQueue.class);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM