class对象:
class A{
public int a1 = 1;
private int a2 =2;
public String s ;
public A(String str,int a){
s=str;
a1 =a;
}
private A(int i){
a1 = i;
}
public A(){}
@Override
public String toString() {
return "A{" +
"a1=" + a1 +
", a2=" + a2 +
", s='" + s + '\'' +
'}';
}
}
反射实例化对象
public class Main {
public static void main(String[] args) throws Exception {
Class class_ = Class.forName("fanshe_chaozhuo.Constructor_.A");
// 调用哪个构造器的格式,且包含传参,最后实例化
// 这是无参构造器的
Object o = class_.getDeclaredConstructor().newInstance();
// 这是有参的写法
Object o1 = class_.getDeclaredConstructor(String.class,int.class).newInstance("aaa",15);
System.out.println(o);
System.out.println(o1);
// 反射机制可以调用私有构造器
try {
Object o2 = class_.getDeclaredConstructor(int.class).newInstance(15);
System.out.println(o2);
}catch (Exception e){
System.out.println("正常情况下实例化私有构造器是会报错的");
System.out.println(e);
}
Constructor constructor = class_.getDeclaredConstructor(int.class);
// 该方法为爆破,使我们可以访问private
constructor.setAccessible(true);
Object o3 = constructor.newInstance(100);
System.out.println(o3);
}
}
运行结果: