26

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);
ironwood
  • 8,936
  • 15
  • 65
  • 114
  • 1
    It's clearly written in the [javadoc](http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#newInstance%28%29) (*Throws* section: "or if the class has no nullary constructor;") – Andreas Dolk Aug 06 '12 at 04:45

2 Answers2

36

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

jmj
  • 237,923
  • 42
  • 401
  • 438
  • Thanks Jigar, got your point. now I'm working on constructor.neWInstance() – ironwood Aug 06 '12 at 05:12
  • You are welcome, [this example](http://www.java2s.com/Code/Java/Reflection/ObjectReflectioninvokeconstructorwithparameters.htm) will help you in that part – jmj Aug 06 '12 at 05:14
  • Thanks for the reference Jigar. I updated the question providing an answer with the help of it. – ironwood Aug 07 '12 at 11:25
  • This answer makes a lot of sense. However, what is wrong with something like [this](https://ideone.com/JS4Ze0) where the class on which `newInstance` is invoked has only one no-arg constructor? – sherrellbc May 21 '18 at 20:18
12

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

kosa
  • 65,990
  • 13
  • 130
  • 167