Shashank Tulsyan Shashank Tulsyan - 1 month ago 18
Java Question

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

Answer

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.

Comments