Video in progress

Strong Middle ⚙️ JVM and memory

What is nest-based access control (Java 11), and how did it change inner classes' access to private members at the bytecode level?

Before Java 11, when an inner class accessed an outer class's private field, javac generated synthetic bridge methods like access$000, because to the JVM they were separate classes. Since Java 11 (JEP 181), classes are declared as a "nest" and the JVM lets the members of one nest access each other's private members directly.

📖 Answer

public class Outer {
    private int counter;

    class Inner {
        void inc() { counter++; }   // Outer's private field
    }
}

In the Java language this has always been allowed. But Inner is a separate Outer$Inner.class file, and the JVM checks private access at the class level.

In Java 8 javac added hidden methods to Outer:

static int access$008(Outer);   // for counter++

And Inner.inc() called that method. The consequences: odd access$ frames in stack traces, an extra method for every private member (a method-limit problem on Android), and no way to reach a private member from inside Inner with reflection.

Since Java 11 class files have new attributes: NestMembers in Outer (the list of Inner classes) and NestHost in Inner (Outer). The JVM grants access based on them:

javap -v Outer\$Inner.class | grep -A2 NestHost
# NestHost: class Outer

Inner.inc() now works directly with getfield/putfield. Calling a nestmate's private method is done with invokevirtual (invokeinterface in an interface).

Reflection was updated too: Class.getNestHost(), getNestMembers(), isNestmateOf().

In practice this affects you directly very little, but it matters for bytecode manipulation libraries and agents, and hidden classes join this mechanism through the NESTMATE option.