Use The Constructor.newInstance
method. The Class.newInstance
method has been deprecated since Java 9 to enhance compiler recognition of instantiation exceptions.
public class Foo {
public Foo()
{
Class newT = null;
instantiateNew(newT);
}
T instantiateNew(Class> clsT)
{
T newT;
try {
newT = (T) clsT.getDeclaredConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException | NoSuchMethodException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return newT;
}
}