Benjamin
Benjamin

Reputation: 628

Returning an instance of a parameter class using generics

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

Answers (3)

Adam Zalcman
Adam Zalcman

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

Thomas
Thomas

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

Stijn Geukens
Stijn Geukens

Reputation: 15628

private <T> T makeNewInstance(Class<T> clazz) throws InstantiationException, IllegalAccessException {
    return clazz.newInstance();
}

Upvotes: 0

Related Questions