Reputation: 628
This might be obvious to many of you but,
How do I convert this (example) function to using generics:
private Object makeNewInstance(Class clazz) throws InstantiationException, IllegalAccessException {
return clazz.newInstance();
}
I was expecting something like this:
private <T> T makeNewInstance(T clazz) throws InstantiationException, IllegalAccessException {
return clazz.newInstance();
}
But the parameter T must be a class and return T an instance of T.
Any help would be appreciated.
Upvotes: 1
Views: 131
Reputation: 27233
Change the argument type to Class<T>
:
private <T> T makeNewInstance(Class<T> clazz) throws InstantiationException, IllegalAccessException {
return clazz.newInstance();
}
See this for more information about Class<T>
and newInstance()
.
Also, depending on your context, you may consider making the makeNewInstance()
method static.
Upvotes: 3
Reputation: 88707
Your parameter should still be of type Class
:
private <T> T makeNewInstance(Class<T> clazz) throws InstantiationException, IllegalAccessException {
return clazz.newInstance();
}
Upvotes: 0
Reputation: 15628
private <T> T makeNewInstance(Class<T> clazz) throws InstantiationException, IllegalAccessException {
return clazz.newInstance();
}
Upvotes: 0