Tim
Tim

Reputation: 355

Instanize java generic class whose constructor takes class object argument

I have SuperQueue class

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

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

}

How can I create a SuperQueue object? I have tried:

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

and

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

Upvotes: 0

Views: 103

Answers (2)

newacct
newacct

Reputation: 122439

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

Upvotes: 0

sol4me
sol4me

Reputation: 15698

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>

In order to create the object, you need to pass a class that Implements Queue<Integer> for e.g.

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

and then you can use it like this

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

Upvotes: 1

Related Questions