简体   繁体   English

实例化其构造函数带有类对象参数的java泛型类

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

I have SuperQueue class 我有SuperQueue类

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

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

}

How can I create a SuperQueue object? 如何创建SuperQueue对象? I have tried: 我努力了:

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

and

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

In your code 在你的代码中

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

you are passing incompatible types because Class<ConcurrentLinkedQueue> cannot be converted to Class<? extends Queue<Integer> 您传递不兼容的类型,因为Class<ConcurrentLinkedQueue>无法转换为Class<? extends Queue<Integer> Class<? extends Queue<Integer>

In order to create the object, you need to pass a class that Implements Queue<Integer> for eg 为了创建对象,您需要传递一个实现Queue<Integer>的类,例如

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

and then you can use it like this 然后你可以像这样使用它

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