根据JEP我链接的评论(也是
here),
A caller-sensitive method varies its behavior according to the class
of its immediate caller. It discovers its caller’s class by invoking
the sun.reflect.Reflection.getCallerClass method.
如果你看看Class#forName(String)的实现,
@CallerSensitive
public static Class> forName(String className)
throws ClassNotFoundException {
return forName0(className, true,
ClassLoader.getClassLoader(Reflection.getCallerClass()));
}
Returns the class of the caller of the method calling this method, ignoring frames associated with java.lang.reflect.Method.invoke() and its implementation.
@CallerSensitive
public static native Class getCallerClass();
在这个JEP之前,似乎这个问题是,如果调用者敏感方法是通过反射而不是直接调用的,那么必须有一个复杂的过程来确定实际的调用类是什么。如果通过反射调用该方法,这是有问题的。提出(并引入)@CallerSensitive的一个更简单的过程。
基本上,@CallerSensitive注释由JVM使用
The JVM will track this annotation and, optionally, enforce the
invariant that the sun.reflect.Reflection.getCallerClass method can only report the caller of a method when that method is marked with this annotation.