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) {
e.printStackTrace();
}
}
This is how to invoke the method.
List<String> myList = new ArrayList<>();
myMethod(myList,String.class);
0 comments:
Post a Comment