How do you use module-aware reflection with a simple code example?

In Java, module-aware reflection provides a way to access modules and their members in a more controlled manner, especially with the introduction of the Java Platform Module System (JPMS) in Java 9. This approach helps in enforcing encapsulation while still allowing necessary access to certain classes and methods across module boundaries.

Here's a simple example to demonstrate how to use module-aware reflection:

// Example Java code module my.module { exports my.package; } package my.package; public class MyClass { public void myMethod() { System.out.println("Hello from myMethod!"); } } // Accessing MyClass using module-aware reflection import my.package.MyClass; import java.lang.module.ModuleFinder; import java.lang.reflect.Method; public class ReflectionExample { public static void main(String[] args) throws Exception { // Find the module Module myModule = MyClass.class.getModule(); // Access MyClass through reflection Class> clazz = Class.forName("my.package.MyClass", true, myModule); Object instance = clazz.getDeclaredConstructor().newInstance(); // Access myMethod and invoke it Method method = clazz.getMethod("myMethod"); method.invoke(instance); } }

module-aware reflection Java Platform Module System JPMS Java reflection example