How has module-aware reflection changed in recent Java versions?

With the introduction of the Java Platform Module System (JPMS) in Java 9, module-aware reflection has undergone significant changes. The enhancements provide mechanisms to enable reflection operations to be more aware of module encapsulation, affecting how classes, methods, and fields are accessed.

Prior to Java 9, reflection provided access to all classes regardless of their visibility. However, with the modular system in place, reflection cannot bypass the access restrictions of modules. This means that a class that is not exported by its module cannot be accessed via reflection if that module's encapsulation is respected.

Mixed with these new rules, Java has introduced specific APIs that allow for easier handling and inspection of modules through reflection, making it easier to work with modular applications.

// Example code demonstrating module-aware reflection Module module = MyClass.class.getModule(); System.out.println("Module Name: " + module.getName()); // Listing all exported packages for (String pkg : module.getPackages()) { System.out.println("Exported Package: " + pkg); } // Checking if a class is accessible boolean isAccessible = module.isOpen("com.example.package") && MyClass.class.getDeclaredConstructor().isAccessible(); System.out.println("Is MyClass accessible: " + isAccessible);

Java Reflection Module-aware Reflection JPMS Java 9 Java Modules