How to use sun.reflect package in jdk9/java-9?

NIrav Modi picture NIrav Modi · Jan 24, 2017 · Viewed 8.6k times · Source

I am using jdk-9 and I want to use sun.reflect.* package in my code but I am getting the below exception

Exception in thread 'main' java.lang.IllegalAccessError : class Test (in moudle: Unnamed Module) cannot access class sun.reflect.Reflaction (in module:java.base), sun.reflect is not exported to Unnamed module

when I run below sample code using JDK-9

public static void main(String args[]){
   System.out.println(Reflection.getCallerClass(3));
}

Answer

Holger picture Holger · Jan 26, 2017

These sun.* packages were never part of the official API and not guaranteed to be present, even in JVMs before Java 9. Be prepared for them to vanish completely in the future, not even be recoverable via some options. Thankfully, there is an official API covering this functionality, eliminating the need for inofficial APIs.

Get the immediate caller class
Class<?> c = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE)
                        .getCallerClass();
Get the n’th caller on the stack (e.g. third, like in your example):
Class<?> c = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).walk(s ->
     s.map(StackWalker.StackFrame::getDeclaringClass).skip(3).findFirst().orElse(null));