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);
Because
Integer
doesn't have no-arg(default) constructor,class.newInstance()
will invoke default constructor internallyClass.newInstance() can only invoke the zero-argument constructor and Integer doesn't have ZERO argument constructor.