What to use instead of Class.newInstance()?

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

1

2 Answers

To quote Java 9's javadoc:

The call

clazz.newInstance()

can be replaced by

clazz.getDeclaredConstructor().newInstance()

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

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like