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);
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.
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 .
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.
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.
Because Integer
doesn't have no-arg(default) constructor, class.newInstance()
will invoke default constructor internally
Class.newInstance() can only invoke the zero-argument constructor and Integer doesn't have ZERO argument constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With