Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics : Obtaining a Class<Collection<T>>?

Tags:

java

generics

I'm having trouble using generics. Given the following example :

class A<T> {
  public A(Class<T> myType){
  }
}

class B<E> extends A<Collection<E>> {
  public B(Class<E> myEType){
    super(???);
  }
}

What ??? should be ? Collection.class don't work... Collection<E>.class neither. (Class<Collection<E>>)Collection.class do not work...

If there is a java generics guru, I need help... :/

like image 662
Yann Le Moigne Avatar asked Feb 29 '12 23:02

Yann Le Moigne


2 Answers

You can't possibly get a Class<Collection<E>> except for Collection.class, because of type erasure. You'll have to use unsafe casts to cast a Collection.class to a Class<Collection<E>> -- specifically, (Class<Collection<E>>) (Class) Collection.class will do the job.

like image 101
Louis Wasserman Avatar answered Nov 05 '22 17:11

Louis Wasserman


class A<T> {
    public A(Class<T> myType){
    }
}

class B<E> extends A<Collection<E>> {
    public B(Class<Collection<E>> myEType){ // <-- this is the changed line
        super(myEType);
    }
}
like image 34
Carl Manaster Avatar answered Nov 05 '22 17:11

Carl Manaster