码迷,mamicode.com
首页 > 编程语言 > 详细

java.lang.InstantiationException-反射机制

时间:2015-05-22 21:01:09      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:

package com.test.classtest;

public class test {

public static void main(String[] args) throws Exception {
String hl = "hello";
String sm = "smile";
String word = "world";
World wr= null;

Hello hello = new Hello(hl);
Smile smile = new Smile(sm);


/*wr = hello;

wr.setSmile(smile);

wr.outPut(hl);
wr.changeWords(sm, hl);
wr.getSmile().smile(word);*/
World world = new World(word);
Smile se = (Smile) Class.forName("com.test.classtest.Smile").newInstance();

}

}

 

Exception in thread "main" java.lang.InstantiationException: com.test.classtest.Smile
at java.lang.Class.newInstance(Class.java:427)
at com.test.classtest.test.main(test.java:23)
Caused by: java.lang.NoSuchMethodException: com.test.classtest.Smile.()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.newInstance(Class.java:412)

 

这个问题要确认三点:

1.不论Class.forName("com.test.classtest.Smile")中的类是否和main函数在同一个包下面,都要写类的全名:包名+类名;

2.实例化的对象是一个接口或者是抽象类等无法被实例化的类

3.使用类反射实例化某个对象时,如果这个对象不包含无参数的构造函数,也会出现这个错误,解决办法是在这个要通过类反射实例化的这个类中添加一个空的无参数构造函数就可以了

 

另:

在Hibernate中就有明确的要求:每一个持久化类都必须带一个不带参数的构造方法。

这里说明一点,如果你在类中声明了带参数的构造函数,会自动覆盖无参数的构造函数,这样系统就无法调用无参数的构造函数实例化类,所以会出现这种错误。

 

java.lang.InstantiationException-反射机制

标签:

原文地址:http://www.cnblogs.com/Jenny5/p/4523170.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!