Java还要再学一遍基础(十五)获取Unsafe

Java中的Unsafe被设计成我们不能随便访问,虽然也可以通过反射获取,但是没有经过严格测试的自己写的代码不能保证它的正确性,这里贴出谷歌api中的Unsafe获取方法,以备后用:

    private static sun.misc.Unsafe getUnsafe() {
        try {
            return sun.misc.Unsafe.getUnsafe();
        } catch (SecurityException tryReflectionInstead) {}
        try {
            return java.security.AccessController.doPrivileged
            (new java.security.PrivilegedExceptionAction() {
                public sun.misc.Unsafe run() throws Exception {
                    Class k = sun.misc.Unsafe.class;
                    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
                        f.setAccessible(true);
                        Object x = f.get(null);
                        if (k.isInstance(x))
                            return k.cast(x);
                    }
                    throw new NoSuchFieldError("the Unsafe");
                }});
        } catch (java.security.PrivilegedActionException e) {
            throw new RuntimeException("Could not initialize intrinsics",
                                       e.getCause());
        }
    }

你可能感兴趣的:(再学一遍java,Java并发)