-1

My code is:

public class MyClass<T extends MyComponent> {
    private T t;
    public MyClass(){
        t = new T();
    }
}

But the compiler don't accept new T(). Is there a way to do this using the constructor MyClass(), without parameters?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
ewerton
  • 427
  • 1
  • 6
  • 13

3 Answers3

3

You could do

public class MyClass<T extends MyComponent> {
    private T t;

    MyClass(Class<T> clazz) throws InstantiationException,
            IllegalAccessException {
        t = clazz.newInstance();
    }

}
mackycheese21
  • 884
  • 1
  • 9
  • 24
Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

Because of type erasure, the JVM doesn't know what T is, so it can't instantiate it. The workaround is to provide a Class<T> and use it to create a new instance:

public MyClass(Class<T> clazz)
{
    t = clazz.newInstance();
}

You'll have to add catching IllegalAccessException and InstantiationException.

rgettman
  • 176,041
  • 30
  • 275
  • 357
1

Not without access to T's class object. Think about it, T could be any subclass of MyComponent, how would you even decide which constructors are available on that particular subclass?

Type erasure means that the compiler silently replaces all "real" references to T with MyComponent.

If you have a reference to Class, you may call Class#newInstance, or get a constructor and invoke that.

Norwæ
  • 1,575
  • 8
  • 18