public class test1 {
public static void main(String[] args)throws Exception {
Class<?> cls = Class.forName("demo6.Book");
Book book = (Book)cls.newInstance();
book.setTitle("JAVA");
book.setPrice(32);
System.out.println(book);
}
}
Exception in thread "main" java.lang.InstantiationException: demo6.Book
at java.lang.Class.newInstance(Unknown Source)
at demo6.test1.main(test1.java:8)
Caused by: java.lang.NoSuchMethodException: demo6.Book.<init>()
at java.lang.Class.getConstructor0(Unknown Source)
... 2 more
检查Book类是否有无参构造
类中必须有无参构造方法吗?
@烧鸭: newInstance只支持无参构造
如果Book类有带参构造,没有无参构造就会报异常
如果不是这个原因,请把Book类代码贴出来
@、熙和: 明白了 谢谢拉