getConstructor()
返回指定参数类型public
的构造器。
getDeclaredConstructor()
返回指定参数类型的private
和public
构造器。
对于getDeclaredConstructor
方法获得的构造器需要先设置可访问,再实例化对象。
public class Test {
public Test() {
System.out.println("HelloTest");
}
public static void main(String[] args) throws Exception {
Constructor c = C.class.getDeclaredConstructor(int.class);
c.setAccessible(true);
c.newInstance(5);
}
}
class C {
public C() {}
private C(int i) {System.out.println("HelloC" + i);}
{System.out.println("I'm C class");}
static {System.out.println("static C");}
}
控制台输出
static C
I’m C class
HelloC5