要实例的类:
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);
}
输出:
我们可以看到代码块和构造方法中的都没有执行,说明绕过了构造器
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/15403.html