187

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

1

2 Answers 2

261

To quote Java 9's javadoc:

The call

clazz.newInstance()

can be replaced by

clazz.getDeclaredConstructor().newInstance()

6
  • 6
    What about java 8?. I can't find getDeclaredConstructor() method without parameters there. Sep 30, 2019 at 6:33
  • 2
    @YuriiKozachok You could use getConstrouctor, although note it will only return public constructors. Also, note that newInstance isn't deprecated in Java 8 (although using it still has all the problems that made the JDK developers deprecate it in 9...)
    – Mureinik
    Sep 30, 2019 at 6:40
  • @Shtefan Where are you seeing that? The java 17 docs don't mark it as deprecated AFAICT: docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/…
    – elhefe
    Oct 22, 2021 at 22:08
  • @elhefe newInstance isn't deprecated. Using newInstance on a class IS deprecated. Dec 9, 2021 at 21:49
  • 3
    @YuriiKozachok getDeclaredConstructor(Class<?>... paramTypes) is variadic - so you can invoke it with 0 arguments. Mar 13, 2022 at 16:29
26
Class.getDeclaredConstructor(...).newInstance(...)

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.