What is an open module in Java 9 and how to use it

后端 未结 2 1180
南旧
南旧 2020-12-15 16:38

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

open module foo {
}

module foo {
}
2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-15 16:51

    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.

提交回复
热议问题