Implementation of nested access control for Java JDK11

  • 2021-06-28 12:28:26
  • OfStack

Java (and other languages) supports nested classes through internal classes.To make it work properly, the compiler performs a few tricks.This is an example:


public class Outer {
  private int outerInt;

   class Inner {
    public void printOuterInt() {
     System.out.println("Outer int = " + outerInt);
    }
  }
}

Before the compilation is performed, the compiler modifies it to create something similar:


public class Outer {
 private int outerInt;

 public int access$000() {
  return outerInt; 
 }

}

class Inner$Outer {

 Outer outer;

 public void printOuterInt() {
  System.out.println("Outer int = " + outer.access$000());
 }
}

Although logically an internal class is part of the same code entity as an external class, it is compiled as a separate class.Therefore, it requires the compiler to create composite bridging methods to provide access to private fields of external classes.

This JEP introduces the concept of a nest in which two members of the same nest (external and internal in our example) are the same nest.Two new properties are defined for the class file formats NestHost and NestMembers.These changes are useful for other languages that support nested classes and compile them as byte codes.

This feature introduces three new methods to java.lang.Class:

Class getNestHost() Class[] getNestMembers() boolean isNestmateOf(Class)

This feature also requires changes to the Java Virtual Machine Specification (JVMS), particularly section 5.4.4 Access Control.


Related articles: