DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Java 27 Makes G1 the Default Everywhere: How to Test Your Small Containers Before You Upgrade
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL

Trending

  • How to Build a Scalable SaaS Product Architecture
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • Top Gen AI Frameworks for Go in 2026: A Hands-On Comparison
  • Architecture Review Boards for Generative AI: A Framework for Governance, Risk Management, and Responsible Adoption

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Java 11 Nest-Based Access Control Via Reflection

Java 11 Nest-Based Access Control Via Reflection

Learn more about nest-based access control via Java 11 reflections.

By 
Anghel Leonard
DZone Core CORE ·
Nov. 19, 19 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
12.4K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Birds in a nest

Learn more about nest-based access control via Java 11 reflections.

Among the features of JDK 11, we have several hotspots (changes at the bytecode level). One of these hotspots is known as JEP 181, or nest-based access control (nests).

Basically, the nest term defines a new access control context that allows classes that are logically part of the same code entity, but which are compiled with distinct class files, to access each other's private members without the need for compilers to insert accessibility-broadening bridge methods (Java documentation).

So, in other words, nests allow nested classes to be compiled to different class files that belong to the same enclosing class. These are then allowed to access each other's private classes without the use of synthetic/bridge methods.

Let's consider the following code:

public class Car {

   private String type = "Dacia";

   public class Engine {

      private String power = "80 hp";

      public void addEngine() {
         System.out.println("Add engine of " + power
            + " to car of type " + type);
      }
   }
}


Let's run javap (the Java class file disassembler tool that allows us to analyze the bytecode) for Car.class in JDK 10. The following screenshot highlights the important part of this code:

Car.class in JDK 10

As we can see, to access the enclosing class field,  Car.type, from the Engine.addEngine() method, Java has altered the code and added a bridge package-private method known as  access$000(). Mainly, this is synthetically generated and can be seen via reflection using the Method.isSynthetic()   and Method.isBridge() methods.

Even if we see (or perceive) the Car  (outer) and Engine (nested) classes as being in the same class, they are compiled to different files (Car.classand  Car$Engine.class). Conforming to this statement, our expectations imply that the outer and the nested classes can access each other's privatemembers. But being in separate files, this is not possible. In order to sustain our expectations, Java adds the synthetic bridge package-private  method,  access$000().

However, Java 11 introduces the nests access control context, which provides support for privateaccess within outer and nested classes. This time, the outer and nested classes are linked to two attributes and they form a nest (we say that they are nestmates). Mainly, nested classes are linked to the NestMembers attribute, while the outer class is linked to the NestHost  attribute. No extra synthetic method is generated.

In the following screenshot, we can see javap being executed in JDK 11 for  Car.class  (notice the NestMembers  attribute):

Car.class and NestMembers in JDK 11

The following screenshot shows the javap  output in JDK 11 for  Car$Engine.class  (notice the NestHost attribute):

JDK 11 Car$Engine.class

Access via the Reflection API

Without nest-based access control, reflection capabilities are also limited. For example, before JDK 11, the following snippet of code would throw IllegalAccessException:

Car newCar = new Car();
Engine engine = newCar.new Engine();

Field powerField = Engine.class.getDeclaredField("power");
powerField.set(engine, power);


We can allow access by explicitly calling  powerField.setAccessible(true):

...
Field powerField = Engine.class.getDeclaredField("power");
powerField.setAccessible(true);
powerField.set(engine, power);
...


Starting with JDK 11, there is no need to call setAccessible().

Moreover, JDK 11 comes with three methods that enrich the Java Reflection API with
support for nests. These methods are Class.getNestHost(),  Class.getNestMembers(), and Class.isNestmateOf().

Let's consider the following Melon class with several nested classes (Slice, Peeler, and Juicer):

public class Melon {
   ...
   public class Slice {
      public class Peeler {}
   }

   public class Juicer {}
   ...
}


Now, let's define a Class for each of them:

Class<Melon> clazzMelon = Melon.class;
Class<Melon.Slice> clazzSlice = Melon.Slice.class;
Class<Melon.Juicer> clazzJuicer = Melon.Juicer.class;
Class<Melon.Slice.Peeler> clazzPeeler = Melon.Slice.Peeler.class;


In order to see NestHostof each class, we need to call  Class.getNestHost():

// class modern.challenge.Melon
Class<?> nestClazzOfMelon = clazzMelon.getNestHost();

// class modern.challenge.Melon
Class<?> nestClazzOfSlice = clazzSlice.getNestHost();

// class modern.challenge.Melon
Class<?> nestClazzOfPeeler = clazzPeeler.getNestHost();

// class modern.challenge.Melon
Class<?> nestClazzOfJuicer = clazzJuicer.getNestHost();


Two things should be highlighted here. First, note that NestHost of Melon is Melon itself. Second, note that NestHostof Peeler is Melon, not Slice. Since Peeler is an inner class of Slice, we may think that its NestHostis Slice, but this assumption is not true.

Now, let's list NestMembers  of each class:

Class<?>[] nestMembersOfMelon = clazzMelon.getNestMembers();
Class<?>[] nestMembersOfSlice = clazzSlice.getNestMembers();
Class<?>[] nestMembersOfJuicer = clazzJuicer.getNestMembers();
Class<?>[] nestMembersOfPeeler = clazzPeeler.getNestMembers();


All of them will return same NestMembers:

[
  class modern.challenge.Melon, 
  class modern.challenge.Melon$Juicer,
  class modern.challenge.Melon$Slice, 
  class modern.challenge.Melon$Slice$Peeler
]


Finally, let's check nestmates:

boolean melonIsNestmateOfSlice
   = clazzMelon.isNestmateOf(clazzSlice); // true

boolean melonIsNestmateOfJuicer
   = clazzMelon.isNestmateOf(clazzJuicer); // true

boolean melonIsNestmateOfPeeler
   = clazzMelon.isNestmateOf(clazzPeeler); // true

boolean sliceIsNestmateOfJuicer
   = clazzSlice.isNestmateOf(clazzJuicer); // true

boolean sliceIsNestmateOfPeeler
   = clazzSlice.isNestmateOf(clazzPeeler); // true

boolean juicerIsNestmateOfPeeler
   = clazzJuicer.isNestmateOf(clazzPeeler); // true


The complete code is available on GitHub.

If you enjoyed this article then you'll love my book, Java Coding Problems that contains a dedicated chapter including 17 problems that involve the Java Reflection API. Thi book is dedicated to Java beginners-intermediates that want to sharp their JDK8-JDK12 skills.

Further Reading

Simple Attribute-Based Access Control With Spring Security

Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Java 27 Makes G1 the Default Everywhere: How to Test Your Small Containers Before You Upgrade
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook