〖反射机制〗Constructor构造器对象
创建对象
package test;
import java.lang.reflect.Constructor;
public class Test {
public String a;
protected String b;
String c;
private String d;
public Test() {}
public Test(String a, String b, String c, String d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
@Override
public String toString() {
return "Test{" +
"a='" + a + '\'' +
", b='" + b + '\'' +
", c='" + c + '\'' +
", d='" + d + '\'' +
'}';
}
public static void main(String[] args) throws Exception {
/ 获取类对象
Class testClass = Class.forName("test.Test");
/ 根据类对象获取Constructor对象
Constructor constructor1 = testClass.getConstructor(String.class, String.class, String.class, String.class);
/ 有参构造器创建对象
Object obj1 = constructor1.newInstance("1", "2", "3", "4");
System.out.println(obj1);
System.out.println("-------------------------------------------------------------------------------------");
/ 空参构造器创建对象(也可以使用testClass.newInstance()创建对象)
Constructor constructor2 = testClass.getConstructor();
Object obj2 = constructor2.newInstance();
System.out.println(obj2);
}
}
运行结果:
我寻见一片海 碧蓝且耀着光
大片船只航行其上 都向着远方
Shared by Foriver_江河