Java Generics : Obtaining a Class>?

后端 未结 3 1404
北荒
北荒 2021-01-18 08:08

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

class A {
  public A(Class myType){
  }
}

class B extends A<         


        
相关标签:
3条回答
  • 2021-01-18 08:21

    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.

    0 讨论(0)
  • 2021-01-18 08:24
    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);
        }
    }
    
    0 讨论(0)
  • 2021-01-18 08:28

    Try this:

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

    If satisfied, please mark this answer correct.

    0 讨论(0)
提交回复
热议问题