Course contentsShow
← Java
Lesson 2530 of 2,87047. Java Platform Module System (JPMS)Free lesson

Using --add-exports and --add-opens as Temporary Workarounds

Apply command-line flags to break encapsulation during migration while finding proper long-term solutions.

Using --add-exports and --add-opens as Temporary Workarounds

What You'll Learn

You'll learn how to use command-line flags to temporarily break module encapsulation during migration while you work toward proper long-term solutions.

The Migration Reality Check

When migrating legacy code to JPMS, you'll often encounter situations where your code depends on internal APIs or uses deep reflection on packages that aren't exported or opened by their modules. Rather than blocking your entire migration, Java provides escape hatches.

Think of these flags as "temporary scaffolding" on a building renovation—they keep things functional while you properly restructure the foundation, but they're not meant to stay forever.

The --add-exports Flag

Use --add-exports when you need to access public types from non-exported packages:

java --add-exports java.base/sun.misc=ALL-UNNAMED --module-path mods -m myapp/com.example.Main

This syntax means: "Allow the unnamed module (classpath code) to access sun.misc from java.base."

You can also export to a specific named module:

--add-exports java.base/sun.misc=myapp.core

The --add-opens Flag

Use --add-opens when frameworks need deep reflection access:

java --add-opens java.base/java.lang=ALL-UNNAMED --module-path mods -m myapp/com.example.Main

This makes java.lang reflectively accessible, allowing setAccessible(true) to work even on private members.

Best Practices

  • Document each flag with a comment explaining why it's needed
  • Create a tracking list of all temporary workarounds
  • Plan replacement strategies for each dependency on internal APIs
  • Use specific module names rather than ALL-UNNAMED when possible
  • Remove flags incrementally as you refactor code

Key Takeaway: --add-exports and --add-opens are temporary band-aids that break encapsulation at the command line—use them to unblock migration, but actively work to eliminate them by finding proper APIs, updating dependencies, or refactoring reflection-heavy code.