Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sun.reflect.Reflection.getCallerClass alternative

From How do I find the caller of a method using stacktrace or reflection? ( as I didn't have enough reputation to comment there itself )

Since sun.reflect.Reflection.getCallerClass has been removed in jdk8, What could be an alternative ?

How about using sun.misc.SharedSecrets

    JavaLangAccess access = SharedSecrets.getJavaLangAccess();
    Throwable throwable = new Throwable();
    int depth = access.getStackTraceDepth(throwable);
    StackTraceElement frame = access.getStackTraceElement(throwable, depth);
like image 452
Sri Nithya Sharabheshwarananda Avatar asked May 22 '14 13:05

Sri Nithya Sharabheshwarananda


2 Answers

I hava code

String callerClass = sun.reflect.Reflection.getCallerClass().getName()

in my project ,while I changed my jdk to 1.8 ,the code throws Exception:

Exception in thread "main" java.lang.InternalError: CallerSensitive annotation expected at frame 1

There are two ways to replace Reflection.getCallerClass()

 StackTraceElement[] elements = new Throwable().getStackTrace();
    String  callerClass = elements[1].getClassName();

or

StackTraceElement[] elements = Thread.currentThread().getStackTrace()
    String  callerClass = elements[1].getClassName();

good luck

like image 106
lishuang Avatar answered Nov 03 '22 11:11

lishuang


As discussed in the comments above. I came to the conclusion to use SharedSecrets.getJavaLangAccess() as explained above in short term, but remove the dependency on sun.* package entirely as a long term solution.

Basically I am changing my requirement itself so that it does not require getCallerClass functionality.

like image 44
Sri Nithya Sharabheshwarananda Avatar answered Nov 03 '22 11:11

Sri Nithya Sharabheshwarananda