Search code examples
javagenericsgeneric-programming

Java Generic type instantiation


There are many questions like this, but none of them seem to answer my question specifically.

How do you instantiate a new T?

I have a generic method, I need to return a new instance of the type in the type parameter. Here is my code...

class MyClass {

  public static MyClass fromInputStream( InputStream input ) throws IOException {

    // do some stuff, and return a new MyClass.

  }
}

Then in a seperate class I have a generic method like so...

class SomeOtherClass {

  public <T extends MyClass>download(URL url) throws IOException {

    URLConnection conn = url.openConnection();

    return T.fromInputStream( conn.getInputStream() );

  }
}

I also tried the following...

class SomeOtherClass {

  public <T extends MyClass>download(URL url) throws IOException {

    URLConnection conn = url.openConnection();

    return new T( conn.getInputStream() ); // Note my MyClass constructor takes an InputStream...

  }
}

But neither permutation of the above will compile! The error is:

File: {...}/SomeOtherClass.java
Error: Cannot find symbol
symbol : class fromInputStream
location : class MyClass

Any suggestions would be appreciated!


Solution

  • I think a common approach is to require the class of type T to be passed in like so:

    class SomeOtherClass {
    
      public <T extends MyClass> T download(Class<T> clazz, URL url) throws IOException {
    
        URLConnection conn = url.openConnection();
    
        return clazz.getConstructor(InputStream.class).newInstance(conn.getInputStream() ); // Note my MyClass constructor takes an InputStream...
    
      }
    }