What is an open module in Java 9 and how do I use it?

user8693774 picture user8693774 · Sep 29, 2017 · Viewed 8.3k times · Source

What is the difference between a module with the open keyword before it and without it? For instance:

open module foo {
}

module foo {
}

Answer

Michał Szewczyk picture Michał Szewczyk · Sep 29, 2017

In order to provide reflective access to your module, Java 9 introduced the open keyword.

You can create an open module by using the open keyword in the module declaration.

An open module grants reflective access to all of its packages to other modules.

For example, if you want to use some framework that heavily relies on reflection, such as Spring, Hibernate, etc, you can use this keyword to enable reflective access for it.

You can enable reflective access for specified packages of your module by using the opens statement in the package declaration:

module foo {
    opens com.example.bar;
}

or by using the open keyword in the module declaration:

open module foo {
}

but keep in mind, that you cannot combine them:

open module foo {
    opens com.example.bar;
}

results with compile-time error.

Hope it helps.