Dmitri Nesteruk
Dmitri Nesteruk

Reputation: 23789

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?

Upvotes: 200

Views: 127433

Answers (2)

Mureinik
Mureinik

Reputation: 311393

To quote Java 9's javadoc:

The call

clazz.newInstance()

can be replaced by

clazz.getDeclaredConstructor().newInstance()

Upvotes: 275

Andy Turner
Andy Turner

Reputation: 140318

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

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

Upvotes: 27

Related Questions