Accessing com.sun.tools.javac.util from Java 9

bramhaag picture bramhaag · Oct 16, 2017 · Viewed 13.3k times · Source

I'm trying to access the List class from com.sun.tools.javac.util. This works fine with Java 8, but when switching to Java 9 I get the following error: Package 'com.sun.tools.javac.util' is declared in module "jdk.compiler", which does not export it to the unnamed module".

I tried adding requires jdk.compiler; to my module-info file, but this did not solve the issue.

Answer

Naman picture Naman · Oct 16, 2017

In the longer run, the safe way to be dealing with such situation is to move away from using these internal APIs of the JDK.

One can make use of the jdk.compiler module's APIs as a replacement to the com.sun.tools.javac package.

Defines the implementation of the system Java compiler and its command line equivalent, javac, as well as javah.

Specifically for com.sun.tools.javac.util.List, almost all of its non-overridden, self-defined methods could be derived from the implementation based on the interface java.util.List.


Migration guide's column about Removed java.* APIs state that -

The Java team is committed to backward compatibility. If an application runs in JDK 8, then it will run on JDK 9 as long as it uses APIs that are supported and intended for external use.

These include:

  • JCP standard, java.*, javax.*
  • JDK-specific APIs, some com.sun.*, some jdk.*

Supported APIs can be removed from the JDK, but only with notice. Find out if your code is using deprecated APIs by running the static analysis tool jdeprscan.

Then to add to the highlighted risk above..

Compile Time

Internal APIs that are encapsulated in JDK 9 are not accessible at compile time, but can be made accessible at compile time via the --add-exports command-line option.

In your case :

--add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED

Run Time

At the runtime, they remain accessible if they were in JDK 8 but in a future release, they will become inaccessible, at which point the --add-exports or --add-opens options can be used to make them accessible at runtime as well.