What to use instead of Class.newInstance()?

JavaReflection

Java Problem Overview


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

Java Solutions


Solution 1 - Java

To quote Java 9's javadoc:

> The call > > clazz.newInstance() > >can be replaced by > > clazz.getDeclaredConstructor().newInstance()

Solution 2 - Java

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDmitri NesterukView Question on Stackoverflow
Solution 1 - JavaMureinikView Answer on Stackoverflow
Solution 2 - JavaAndy TurnerView Answer on Stackoverflow