Wednesday, September 23, 2015

How to create instance from generic type

It’s easy to explain this in code.

  public <T> void myMethod(List<T> list) {
T t;
// t = new T(); // This is basically what you want,
// but will cause compile error.

Strictly speaking, you can NOT create instances of type parameters. But you can reach the same goal by using reflection and one more parameter.

  public <T> void myMethod(List<T> list, Class<T>cls) {
T t;
// t = new T(); // This is what you want to do
// but will cause compile error.
try {
t = cls.newInstance(); // use reflection to create instance
} catch (InstantiationException | IllegalAccessException e) {

This is how to invoke the method.

  List<String> myList = new ArrayList<>();


Post a Comment

Powered by Blogger.

About The Author

My Photo

Has been a senior software developer, project manager for 10+ years. Dedicate himself to Alcatel-Lucent and China Telecom for delivering software solutions.


Unordered List