package mrliu.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Test {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Class clazz = Class.forName("mrliu.reflect.Person");
Constructor c = clazz.getConstructor(null);
Person p = (Person) c.newInstance(null);
// Constructor c = clazz.getConstructor(String.class);
// Person p3 = (Person) c.newInstance("ddd");
// Person p2 = (Person) clazz.newInstance();
}
}
package mrliu.reflect;
public class Person {
Person(){
System.out.println("person()");
}
Person(String p){
System.out.println("person()"+p);
}
}
为什么会报错呢?
Exception in thread "main" java.lang.NoSuchMethodException: mrliu.reflect.Person.<init>()
at java.lang.Class.getConstructor0(Class.java:2706)
at java.lang.Class.getConstructor(Class.java:1657)
at mrliu.reflect.Test.main(Test.java:15)
明明有构造函数啊
------解决思路----------------------
构造方法前面加上public... 否则构造方法是不能在外部调用, 就造成了不能在外部new出对象....