四时宝库

程序员的知识宝库

通过rt.jar包中的sun.misc.Unsafe实例化无构造方法实例

import java.io.Serializable;
import java.lang.reflect.Field;
import sun.misc.Unsafe;

public class Demo {
    public static void main(String[] args) {
        try {
            Field f = Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);
            Unsafe unsafe = (Unsafe) f.get(null);
            Test1 t6 = (Test1) unsafe.allocateInstance(Test1.class);
            t6.say("unsafe Test");
        } catch (NoSuchFieldException | SecurityException | InstantiationException | IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}


class Test1 implements Cloneable, Serializable {
    private static final long serialVersionUID = -8655076206703674175L;

    public Test1() {
        throw new Error("不能创建实例");
    }

    public void say(String str) {
        System.out.println(str);
    }

    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接