Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InstantiationException for newInstance() [duplicate]

Tags:

Following works fine when the className is "java.awt.Rectangle" and "java.lang.String" etc. But it fails for "java.lang.Integer", "java.lang.Double" giving java.lang.InstantiationException for classDefinition.newInstance().

Class classs = Class.forName(className); Object object = classs.newInstance(); 

Is this a problem with the Wrapper classes or another?

Editted : Way to do this - credits should go to Jigar.

Class       integerDefinition   = Class.forName("java.lang.Integer"); Constructor intArgsConstructor  = integerDefinition.getConstructor(new Class[] {int.class}); Object[]    intArgs             = new Object[] { new Integer(12) }; Object      object              = intArgsConstructor.newInstance(intArgs); 
like image 842
namalfernandolk Avatar asked Aug 06 '12 04:08

namalfernandolk


People also ask

How do I fix Java Lang InstantiationException?

How to Resolve InstantiationException. To avoid the InstantiationException , it should be ensured that the instance of the class that is attempted to be created at runtime using Class. newInstance() is a concrete class and not an abstract class, interface, array class, primitive or void.

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 .

Why newInstance method was deprecated?

These calls can be replaced with a call to clazz. getDeclaredConstructor(). newInstance(). The reason for the deprecation is that that path bypasses compile-time exception checking.

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.


2 Answers

Because Integer doesn't have no-arg(default) constructor, class.newInstance() will invoke default constructor internally

like image 93
jmj Avatar answered Oct 19 '22 07:10

jmj


Class.newInstance() can only invoke the zero-argument constructor and Integer doesn't have ZERO argument constructor.

like image 43
kosa Avatar answered Oct 19 '22 07:10

kosa