Java.lang.InternalError: CallerSensitive annotation expected in frame 1

In a static method (annotated using @CallerSensitive ) I try to get the name of the calling class:

 @CallerSensitive public static void someMethod() { String name = sun.reflect.Reflection.getCallerClass().getName(); ... } 

I get an error message:

 java.lang.InternalError: CallerSensitive annotation expected at frame 1 

What is wrong here?

References

UPDATE

I am using java 8 (u25) and the getCallerClass() method is not deprecated ( getCallerClass(int) deprecated), as seen by disassembling the bytecode:

 $ /usr/lib/jvm/java-8-oracle/bin/javap -cp /usr/lib/jvm/java-8-oracle/jre/lib/rt.jar -verbose sun.reflect.Reflection > bytecode 

Exit (only relevant lines are displayed)

 Classfile jar:file:/usr/lib/jvm/jdk1.8.0_25/jre/lib/rt.jar!/sun/reflect/Reflection.class Last modified Sep 17, 2014; size 6476 bytes Compiled from "Reflection.java" public class sun.reflect.Reflection minor version: 0 major version: 52 flags: ACC_PUBLIC, ACC_SUPER Constant pool: #78 = Utf8 Lsun/reflect/CallerSensitive; #80 = Utf8 Deprecated #82 = Utf8 Ljava/lang/Deprecated; { public sun.reflect.Reflection(); descriptor: ()V flags: ACC_PUBLIC public static native java.lang.Class<?> getCallerClass(); descriptor: ()Ljava/lang/Class; flags: ACC_PUBLIC, ACC_STATIC, ACC_NATIVE Signature: #76 // ()Ljava/lang/Class<*>; RuntimeVisibleAnnotations: 0: #78() public static native java.lang.Class<?> getCallerClass(int); descriptor: (I)Ljava/lang/Class; flags: ACC_PUBLIC, ACC_STATIC, ACC_NATIVE Deprecated: true Signature: #81 // (I)Ljava/lang/Class<*>; RuntimeVisibleAnnotations: 0: #82() 
+5
source share
2 answers

Only this privileged code can use this annotation. code has the privilege if it is loaded through the bootstrap bootloader or the extension class loader.

excerpt from the open source JDK file classFileParser.cpp

  // Privileged code can use all annotations. Other code silently drops some. const bool privileged = loader_data->is_the_null_class_loader_data() || loader_data->is_ext_class_loader_data() || loader_data->is_anonymous(); 
+8
source

getCallerClass() is removed from Java8. When I run this example in Java 8, I get the same error. Starting with Java 7 (1.7.0_55) I get the name of the calling class. In any case, I would refrain from using anything directly from the sun. * Package hierarchy.

To get the name of the calling class, you can do the following (I just used the instance initializer to get the name, you must get from the SecurityManager and provide the getCallerClass () method in your class):

 public static void someMethod() { new SecurityManager() { { String name = getClassContext()[1].getSimpleName(); System.err.println(name == null ? "null" : name); } }; } 
0
source

Source: https://habr.com/ru/post/1210171/


All Articles