Java 9 Nested (Hierarchical or Parent/Child) Modul

2020-07-30 06:49发布

问题:

Is it possible to create inheritance-based (or nested) modules in Java 9?

Something like this:

module a
   |
   ├── module a1
   |   
   └── module a2

In this example, both the a1 and a2 modules are children of a.

If I import either of the child modules, I would get the functionality of the parent (a) along with any functionality defined in that child. That is, I could import a1, and explicitly gain access to the functionality of both a and a1 (but not a2).

Both a1 and a2 are an a, and can access all of the packages of a, without having to expose the packages of a to them.

回答1:

You can emulate what you asked for with a combination of requires transitive and exports to syntax:

  • requires transitive: Specifies that importing this module will inherently import another module. You can use this to ensure that a1 and a2 cause a to be imported.
  • exports to: This will let you export functionality to a specific module only; this will allow you to let a give access to a1 and a2 functionality that would be dangerous to have publicly exported.

So, for examples sake:

module a {
    exports com.internal to a1;
    exports com.internal to a2;
}

module a1 {
    requires transitive a;
}

module a2 {
    requires transitive a;
}

In this case, if a consumer depends on a1, they will inherently depend on a (thus gaining the utilities of both), and the com.internal package, while visible to a1 for internal use, will not be externally visible to the consumer.

It is not quite what you asked for. a1 is not an a. Further, a1 can not be made to be an a; the JLS does not allow for wildcards in exports (IE: exports * to a1, which still wouldn't make a1 an a but would bring it closer from a pragmatic perspective), and no other syntax exists in modules to allow for it.



标签: java java-9