Java注解之@CallerSensitive

                <svg xmlns="http://www.w3.org/2000/svg" style="display: none">
                    <path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0)"></path>
                </svg>
                <h1><a id="_0"></a>前言<button class="cnblogs-toc-button" title="显示目录导航" aria-expanded="false"></button></h1> 

有一天在看 Unsafe.getUnsafe() 源码时,发现该方法上有一个 @CallerSensitive 注解。类似的,在 Class.forName 方法也有该注解。它们的源码分别如下:

@CallerSensitive
public static Unsafe getUnsafe() {
    Class var0 = Reflection.getCallerClass();
    if (!VM.isSystemDomainLoader(var0.getClassLoader())) {
        throw new SecurityException("Unsafe");
    } else {
        return theUnsafe;
    }
}
@CallerSensitive
public static Class<?> forName(String className)
            throws ClassNotFoundException {
    Class<?> caller = Reflection.getCallerClass();
    return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
}

这 2 个方法有个共同点,就是内部都调用了 Reflection.getCallerClass(),这是一个 native 方法。凑巧的是,Reflection.getCallerClass() 也有 @CallerSensitive 注解

@CallerSensitive
public static native Class<?> getCallerClass();

解释

  • Caller= 调用者,Sensitive= 敏感的 / 易感知的。顾名思义,主要是针对于方法调用者所做的一些控制。

  • Reflection.getCallerClass() 要求调用者必须有 @CallerSensitive 注解,并且必须有权限(由 bootstrap class loader 或者 extension class loader 加载的类)才可以调用。本地测试需要加上启动参数
    在这里插入图片描述

  • Reflection.getCallerClass() 加了 @CallerSensitive 注解后,能够跟踪到最初的调用者。例如 method-1 -> method-2 -> method-3 -> method-4 -> Reflection.getCallerClass,最终返回的是 method-1

  • @CallerSensitive 能够堵住反射的漏洞,当你尝试用反射调用 Reflection.getCallerClass(),结果会抛出异常

其他

  • 这个方法没找到太多的资料,在我们日常开发中,可以说作用不大,了解就行
  • 主要还是 JDK 底层控制权限的地方使用。