Java 9 replace Class.newInstance

  • A+
Category:Languages

Class.newInstance was deprecated in Java 9:

clazz.newInstance() 

can be replaced by

clazz.getDeclaredConstructor().newInstance() 

The problem is that getDeclaredConstructor returns any constructor without regarding the access level.

If I want to replace all occurrences in my code (on different packages/access level) should I use getConstructor to get the public constructor?

the Constructor object of the public constructor that matches the specified parameterTypes

Or can't I bulk replace all occurrences because it needs to be per case (if a public constructor exists and/or if I have the right access level for the class)?

EDIT

getDeclaredConstructor:

   return getConstructor0(parameterTypes, Member.DECLARED); 

getConstructor:

   return getConstructor0(parameterTypes, Member.PUBLIC); 

 


Class.newInstance() invokes the zero-argument constructor, whether it is public or not. It performs a runtime check of the caller's access to that constructor.

Calling getDeclaredConstructor() returns that same constructor. Calling getDeclaredConstructor().newInstance() performs the same runtime checks. Except for the different handling of exceptions, it does the same thing.

No, don't change it to getConstructor(). That would cause a NoSuchMethodException for non-public constructors.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: