Skip to main content
added 79 characters in body; deleted 21 characters in body; added 156 characters in body
Source Link
sbridges
  • 25.2k
  • 4
  • 66
  • 72

No you can't do new T(), since you don't know if T has a no arg constructor, and because the type of T is not present at runtime due to type erasure.

To create an instance of T, you need to have code like,

public <T> T create(Class<T> clazz) {
    try {
        //T must have a no arg constructor for this to work 
        return clazz.newInstance(); 
    } catch (InstantiationException e) {
        throw new IllegalStateException(e);
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(e);
}

No you can't do new T(), since you don't know if T has a no arg constructor.

To create an instance of T, you need to have code like,

public <T> T create(Class<T> clazz) {
    try {
        return clazz.newInstance();
    } catch (InstantiationException e) {
        throw new IllegalStateException(e);
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(e);
}

No you can't do new T(), since you don't know if T has a no arg constructor, and because the type of T is not present at runtime due to type erasure.

To create an instance of T, you need to have code like,

public <T> T create(Class<T> clazz) {
    try {
        //T must have a no arg constructor for this to work 
        return clazz.newInstance(); 
    } catch (InstantiationException e) {
        throw new IllegalStateException(e);
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(e);
}
Source Link
sbridges
  • 25.2k
  • 4
  • 66
  • 72

No you can't do new T(), since you don't know if T has a no arg constructor.

To create an instance of T, you need to have code like,

public <T> T create(Class<T> clazz) {
    try {
        return clazz.newInstance();
    } catch (InstantiationException e) {
        throw new IllegalStateException(e);
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(e);
}