1: new
2:Constructor反射
3:Test.class.newInstance() 须有默认构造函数
4:Objenesis 是否存在默认构造函数都可以创建,但没有参数无法init
public class Test {
private String string;
public Test(String string) {
this.string = string;
}
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
@Override
public String toString() {
return "Test{" +
"string='" + string + '\'' +
'}';
}
public static void main(String[] args) {
Test o1 = new Test("test1");
System.out.println("o1:" + o1);
Objenesis objenesis = new ObjenesisStd();
try {
Test o2 = Test.class.newInstance(); //报错,须有默认构造函数
System.out.println("o2:" + o2);
} catch (Exception e) {
e.printStackTrace();
}
try {
Constructor<Test> constructor = Test.class.getConstructor(String.class);
constructor.setAccessible(true);
Test o3 = constructor.newInstance("test2");
System.out.println("o3:" + o3);
} catch (Exception e) {
e.printStackTrace();
}
ObjectInstantiator<Test> objectInstantiator = objenesis.getInstantiatorOf(Test.class);
Test o4 = objectInstantiator.newInstance();
System.out.println("o4:" + o4);
Test o5 = objectInstantiator.newInstance();
System.out.println("o5:" + o5);
}
}