java. Lang. internalerror: callersensitive comment expected in frame 1

In a static method (annotated with @ callersensitive), I try to get the name of the calling class:

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

I received an error:

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

What's wrong with that?

reference resources

> http://www.infoq.com/news/2013/07/Oracle-Removes-getCallerClass > http://openjdk.java.net/jeps/176

UPDATE

I am using java 8 (u25) and do not recommend the method getcallerclass () (getcallerclass (int)) as you can see when disassembling 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

Output (only relevant rows 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_NATIVE
Deprecated: true
Signature: #81                          // (I)Ljava/lang/Class<*>;
RuntimeVisibleAnnotations:
  0: #82()

Solution

Only privileged code can use this annotation

Extracted from the open JDK source 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();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>