Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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));
}
like image 584
NIrav Modi Avatar asked Jan 24 '17 04:01

NIrav Modi


1 Answers

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));
like image 130
Holger Avatar answered Sep 25 '22 06:09

Holger