Access restriction on class due to restriction on required library rt.jar?
If you are getting an "access restriction" error on a class in your Java code, it means that you are trying to access a class or member (field or method) that has restricted access.
If you are getting an "access restriction" error or warning on a class in your Java code, it typically means you are trying to use a class or member (field or method) that is marked as restricted or internal by the Java platform. This is common when using packages like sun.* or com.sun.*, which are not part of the official public API. Note that rt.jar is an outdated reference; since Java 9, the JDK is modularized, and internal APIs are handled by the module system rather than a single JAR file.
To resolve this, you should first check if a public alternative exists in the standard Java API. For example, instead of relying on internal utilities, use the standard java.lang.reflect or java.lang.invoke packages:
// ❌ Restricted internal API (triggers access restriction warning)
// import sun.misc.Unsafe;
// ✅ Recommended public alternative
import java.lang.reflect.Field;
import java.lang.invoke.MethodHandles;
public class Example {
public static void main(String[] args) throws Exception {
Field field = Example.class.getDeclaredField("someField");
field.setAccessible(true);
}
}If you are using an IDE like Eclipse or IntelliJ IDEA, you can adjust the compiler warning level for restricted APIs in your project settings. For build tools like Maven or Gradle, you can configure the compiler to suppress these warnings, though this is not recommended for production code.
Note: Since Java 9, strong encapsulation blocks reflective access to internal APIs by default. If you absolutely must access restricted packages, you need to pass explicit JVM flags (e.g., --add-opens) or configure your build tool to add them. However, using reflection on internal classes is slower, more error-prone, and unsupported, so it should generally be avoided unless absolutely necessary.