Search code examples
javareflectionjava-9java-modulemodule-info

How do Java Module directives impact reflection access into a module?


According to https://www.oracle.com/corporate/features/understanding-java-9-modules.html, the Java Module system introduces the following directives:

  • exports, exports ... to
  • uses
  • provides ... with
  • open, opens, opens ... to

What (if any) impact does each directive have on an external module accessing internal members using reflection?

For example, does exports <package> allow external modules to access all public, protected, private members of the exported package using reflection? What about the other directives?


Solution

  • I would simply quote the #JLS7.7 here (formatted and categorized by me):

    Distinct from access at compile time and access at runtime, the Java SE Platform provides reflective access via the Core Reflection API (§1.4).

    More towards your question categorising as Normal module(module foo) and Open module (open module bar):

    Normal Module

    A normal module grants reflective access to types in only those packages which are explicitly exported or explicitly opened (or both).

    • the module's exported packages (exports com.example.foo.bar)

      For code outside a normal module, the reflective access granted to types in the module's exported (and not opened) packages is specifically to the public and protected types in those packages, and the public and protected members of those types.

    • the module's opened packages (opens com.example.foo.internal to com.example.bar)

      The reflective access granted to types in the module's opened packages (whether exported or not) is to all types in those packages, and all members of those types.

      No reflective access is granted to types, or their members, in packages which are not exported or opened.

    • within a module

      The code inside the module enjoys reflective access to all types, and all their members, in all packages in the module.

    Open Module

    An open module grants reflective access to types in all its packages, as if all packages had been opened.

    • the module's opened packages

      For code outside an open module, the reflective access granted to types in the module's opened packages (that is, all packages in the module) is to all types in those packages, and all members of those types.

    • within a module

      Code inside the module enjoys reflective access to all types, and all their members, in all packages in the module.