Getting a class with Class.forName

Take a look at this line below:

targetClass = Class.forName(className).newInstance().getClass(); 

My question here is why it calls newInstance (). getClass ();

Is it enough to write

 targetClass = Class.forName(className); 

?

+4
source share
2 answers

It makes no sense to call newInstance().getClass() , because it will give the same Class instance where it was created from.

Rather, it creates an additional instance that will be immediately deleted. Even this will not work if the class does not have a default constructor.

In addition, the cost of creating, initializing, etc. may be wonderful.

+3
source

Yes.

 Class<T> targetClass = Class<T>.forName(className); 

And in creating objects it is better to use getConstructor.

 T obj = targetClass.getConstructor().newInstance(); 

A call to Class.newInstance shows the problem identified in javadoc.

+2
source

All Articles