Java 9 replace Class.newInstance
These two calls invoke the same constructor, the zero-argument constructor:
klass.newInstance()
klass.getDeclaredConstructor().newInstance()
Both perform the same run-time check to verify the caller's access, if the constructor is not public. The only difference is that #2 wraps any checked exceptions instead of directly throwing. Otherwise they are identical and you can replace one with the other.
But this is different:
klass.getConstructor().newInstance()
because it can only return a public constructor. It throws a NoSuchMethodException
if the constructor is not public.
So you can't change it to getConstructor()
unless you know the constructor is public.
user7294900
Java developer with full stack capabilities and software testing background
Updated on June 07, 2022Comments
-
user7294900 almost 2 years
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);
-
user7294900 over 5 yearsThank you, so any exceptions thrown will only be a valid initialization failures?
-
Boann over 5 years@user7294900 Yes.