InstantiationException for newInstance() [duplicat

2020-05-25 07:48发布

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);

2条回答
老娘就宠你
2楼-- · 2020-05-25 08:24

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

查看更多
男人必须洒脱
3楼-- · 2020-05-25 08:28

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

查看更多
登录 后发表回答