要实例的类:
public class BlogDto2 {
private Integer id;
private String name;
{
System.out.println("11111");
}
public BlogDto2(Integer id, String name) {
this.id = id;
this.name = name;
System.out.println("22222");
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "BlogDto{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
方法一:
@Test
public void test3() throws Exception {
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
Unsafe unsafe = (Unsafe) theUnsafe.get(null);
BlogDto2 blogDto2 = (BlogDto2) unsafe.allocateInstance(BlogDto2.class);
System.out.println(blogDto2);
}
输出:
方法二:
@Test
public void test4() {
Objenesis o = new ObjenesisStd();
ObjectInstantiator<BlogDto2> instantiatorOf = o.getInstantiatorOf(BlogDto2.class);
BlogDto2 blogDto2 = instantiatorOf.newInstance();
System.out.println(blogDto2);
}
输出:
我们可以看到代码块和构造方法中的都没有执行,说明绕过了构造器