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

opens vs exports: Key Differences

Compare opens (reflection-only access) with exports (compile-time and runtime access) to understand when to use each.

opens vs exports: Key Differences

What you'll learn: You'll understand the critical distinction between opens (reflection-only access) and exports (compile-time and runtime access) to choose the right directive for your module's needs.


Both opens and exports control package visibility in JPMS, but they grant different levels of access to other modules.

exports: Public API Access

When you export a package, you're making its public types available for:

  • Compile-time access (other modules can compile against it)
  • Runtime access (normal method calls, field access)
  • Reflection access (as a side effect)

Think of exports as opening the front door of your house: invited guests can walk right in and use everything normally.

module mymodule {
    exports com.example.api;  // Full access to public types
}

opens: Reflection-Only Access

When you open a package, you're allowing deep reflection access to:

  • Private fields, methods, and constructors
  • Protected and package-private members
  • But NOT compile-time access

Think of opens as giving someone an X-ray vision device: they can see and manipulate everything inside your house, but they can't walk through the front door normally.

module mymodule {
    opens com.example.internal;  // Reflection only, no compile access
}

When to Use Each

  • Use exports for your public API—classes you want other modules to depend on and use directly
  • Use opens for frameworks that need reflection (like Spring, Hibernate, or JUnit) but aren't part of your intended API

You cannot compile code that references types in an opens-only package, but reflection will work at runtime.

Key Takeaway: exports grants full compile-time and runtime access for normal usage; opens grants only runtime reflection access without exposing the package as a compile-time dependency.