What to use instead of Class.newInstance()?

2019-06-15 00:14发布

问题:

Class.newInstance() is marked deprecated. Documentation does not suggest any alternatives. How are we meant to create instances now?

回答1:

To quote Java 9's javadoc:

The call

clazz.newInstance()

can be replaced by

clazz.getDeclaredConstructor().newInstance()



回答2:

Class.getDeclaredConstructor(...).newInstance(...)

Refer to Google errorprone's documentation (for example) for a description of why.