16

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);
Community
  • 1
  • 1
  • Try http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#getStackTrace() (note that it will return `Thread.getStackTrace` and the current method as the first 2 stack elements) – DankMemes May 22 '14 at 13:53
  • Invoking that will cause the entire stack trace to be created, very inefficient. I just want access to the frame at certain depth. Actually, the alternative which I suggested, probably that will also create the full stack trace. I am not sure. – Sri Nithya Sharabheshwarananda May 22 '14 at 13:57
  • 3
    I would say avoid using `sun.*` packages because they won't be there on all platforms and java configurations. Also, why would getting the entire stack trace be inefficient? Do you have a lot of things in the stack, or do you need this at a high rate? Don't worry about efficiency unless it actually makes a difference – DankMemes May 22 '14 at 14:13
  • I use it somewhere in my code for debugging purpose. In long term, I will remove it, but for now I might have to resort to the method explained above. – Sri Nithya Sharabheshwarananda May 22 '14 at 14:17
  • @ZoveGames could you add your answer as an actual Answer instead of just a comment? – Cel Skeggs Mar 29 '15 at 07:40

2 Answers2

4

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.

BuZZ-dEE
  • 6,075
  • 12
  • 66
  • 96
4

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

BuZZ-dEE
  • 6,075
  • 12
  • 66
  • 96
lishuang
  • 81
  • 1