Skip to content
Advertisement

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

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

open module foo {
}

module foo {
}

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement