0

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
    }
}
Dan Dv
  • 315
  • 2
  • 11
  • 3
    `T` is undefined at runtime, because there's only one copy of the byte code. So the JVM can't tell which class to instantiate. – Dawood ibn Kareem Jul 19 '14 at 12:20
  • 5
    If you could, what would happen if `T` didn't have a no-args constructor, or it was private, or `T` was an interface? (What would `new genericClass().foo()` do?) – user253751 Jul 19 '14 at 12:20
  • 2
    Because `T` is not real -- it's just a fig newton of the compiler's imagination. There is no constuctor to call -- the type of `T` is not even known at runtime. – Hot Licks Jul 19 '14 at 12:22
  • possible duplicate of [Create instance of generic type in Java?](http://stackoverflow.com/questions/75175/create-instance-of-generic-type-in-java) – Drazen Bjelovuk Aug 23 '14 at 01:16

2 Answers2

6

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();
  }
}
NoDataFound
  • 9,100
  • 27
  • 52
1

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.

svenslaggare
  • 428
  • 4
  • 5