Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the sun.reflect.CallerSensitive annotation mean?

What is implied by @CallerSensitive annotation above methods?

For example,the annotation is present in getClassLoader method of Class

 @CallerSensitive     public ClassLoader getClassLoader() {     //     } 
like image 308
Kumar Abhinav Avatar asked Mar 25 '14 06:03

Kumar Abhinav


1 Answers

According to the JEP I linked to in the comments (also 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.

If you look at the implementation of Class#forName(String)

@CallerSensitive public static Class<?> forName(String className)             throws ClassNotFoundException {     return forName0(className, true,                     ClassLoader.getClassLoader(Reflection.getCallerClass())); } 

, you notice that it is using Reflection.getCallerClass(). If we look at that method

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(); 

The problem, it seems, before this JEP, was that if the caller sensitive method was called through reflection instead of directly, there had to be a complex process to identify what the actual calling class was. This was problematic if the method was invoked through reflection. A simpler process was proposed (and introduced) with @CallerSensitive.

Basically, the @CallerSensitive annotation is used by the 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.

like image 147
Sotirios Delimanolis Avatar answered Sep 18 '22 09:09

Sotirios Delimanolis