Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 9 replace Class.newInstance

Tags:

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);
like image 515
user7294900 Avatar asked Nov 12 '18 06:11

user7294900


People also ask

What can I use instead of newInstance?

newInstance() has been deprecated (see https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/Class.html#newInstance() ). These calls can be replaced with a call to clazz. getDeclaredConstructor(). newInstance().

What does class newInstance () do?

Class. newInstance() throws any exception thrown by the constructor, regardless of whether it is checked or unchecked. Constructor. newInstance() always wraps the thrown exception with an InvocationTargetException .

What is newInstance in Java?

The java. lang. Class. newInstance() creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list.

What is the difference between new and newInstance in Java?

In Java, new is an operator where newInstance() is a method where both are used for object creation. If we know the type of object to be created then we can use a new operator but if we do not know the type of object to be created in beginning and is passed at runtime, in that case, the newInstance() method is used.


1 Answers

These two calls invoke the same constructor, the zero-argument constructor:

  1. klass.newInstance()
  2. 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:

  1. 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.

like image 172
Boann Avatar answered Oct 11 '22 10:10

Boann