Avoid Internal JDK sun.* and com.sun.* Packages

ID

java.avoid_sun_packages

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

imports, reliability

Description

Reports import declarations that reference internal JDK packages (sun. or com.sun.).

Rationale

The sun. and com.sun. packages are internal implementation details of the JDK. They are not part of the official Java SE API and may change or be removed between JDK releases without notice. Starting with JDK 9 and the Java Platform Module System (Jigsaw), access to these internal APIs is actively restricted, causing IllegalAccessError at runtime unless explicit --add-opens or --add-exports flags are passed to the JVM.

// Bad -- relies on internal JDK implementation
import sun.misc.Unsafe;
import com.sun.net.httpserver.HttpServer;

Note: this rule flags import declarations only. Fully-qualified inline references (e.g. sun.misc.Unsafe.getUnsafe()) are not covered.

Remediation

Replace internal API usage with official Java SE equivalents or well-maintained third-party libraries:

// Good -- use the public API
import java.lang.invoke.VarHandle;         // instead of sun.misc.Unsafe
import com.sun.net.httpserver.HttpServer;   // already in java.net.http since JDK 11

When no public replacement exists, isolate the internal usage behind an abstraction layer so it can be swapped out when upgrading the JDK.