Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor with generic class is undefined

I'm stuck with a stupid problem I do not understand.

class Foo<T extends Collection<E>, E> {
  private Class<T> collectionClass;
  private Class<E> elementClass;

  public Foo(Class<T> collectionClass, Class<E> elementClass) {
       this.collectionClass = collectionClass;
       this.elementClass = elementClass;
  }
} 

When I try to run this

Foo<Collection<String>, String> foo = 
    new Foo<Collection<String>, String>(
        Collection.class,
        String.class);

I get a compiler error

java.lang.Error: Unresolved compilation problem: 
The constructor Foo<Collection<String>,String>(Class<Collection>, Class<String>) is undefined

Why ? If I erase generics, it's ok

Foo foo = 
    new Foo(
        Collection.class,
        String.class);

If somebody has an idea, it will be great and stop me to bang my head on wall.

like image 646
MarcDeXeT Avatar asked Dec 18 '25 14:12

MarcDeXeT


1 Answers

There is no such thing as a Collection<String>.class, is the problem. Your alternatives include

  • don't use reflection; why are you using reflection?
  • accept the need for an unsafe cast
  • use one of the various tools for referring to generic types at runtime, such as Guava's TypeToken
like image 194
Louis Wasserman Avatar answered Dec 20 '25 04:12

Louis Wasserman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!