Dan Dv
Dan Dv

Reputation: 493

In Java, why can't you use a constructor on generic classes?

What's the logic behind the limitaion of doing the following in Java?

public class genericClass<T>{
    void foo(){
       T t = new T(); //Not allowed
    }
}

Upvotes: 0

Views: 99

Answers (2)

svenslaggare
svenslaggare

Reputation: 438

In Java, generics is implemented using type erasure which means generic type information is erased at compile time. This means that the information for constructing the object isn't available at runtime.

Upvotes: 1

NoDataFound
NoDataFound

Reputation: 11979

Because of type erasure.

The runtime does not know the "real" type of T, it is Object for it. You code would be more or less read like this:

public class genericClass {
    void foo(){
       Object t = new Object(); //Not allowed
    }
}

If you need to do such a thing, you need to use reflection:

public class GenericClass<T> {
  private final Class<? extends T> clazz;
  public GenericClass(Class<? extends T> clazz) {
    this.clazz = clazz;
  }
  void foo() {
    T t = clazz.newInstance();
  }
}

Upvotes: 6

Related Questions