How will JDK9 modules help package subpackages?

I'm curious about JDK9 modules. Let's say you have the following 3 packages:

com.company.product com.company.product.impl_a com.company.product.impl_b 

Classes in product.impl_a and product.impl_b packages can only be accessed by classes in product package. The user should use only classes from the product package. You can imagine that passing certain flags or properties will determine whether impl_a or impl_b will be used internally.

In JDK8- you must make these classes inside impl_a and impl_b public . This sucks because users can be tricked into using these classes. This is perfectly acceptable and permitted.

How can JDK9 help here? We will declare a module for product.impl_a and one more for product.impl_b and declare that the exported classes should be accessible only to the third module product , which will depend on the two modules product.impl_a and product.impl_b ? Also, would it be impossible to declare a new module that will depend on product.impl_a or product.impl_b ? Can other modules depend only on the product module?

+5
source share
2 answers

Nothing in your question indicates that these three packages should end on different JARs / modules. If they do not, just put them in the same JAR, use the visibility modifiers as described, and use the following module declaration:

 module com.company.product { export com.company.product; } 

Then, inside the com.company.product module, you can use the code from all packages, as usual, but from outside only com.company.product is available .

+4
source

You can allow classes inside impl_a and impl_b be public and export packages to specific module (qualified export). Then you can use the convention as:

 exports com.company.product.impl_b to third.module; 

So, in your case, consider these

 module first.module { export com.company.product.impl_a to second.module; export com.company.product.impl_b to third.module; } 

which means that the package com.company.product.impl_a only exported to second.module , which now, when it reads first.module , has access to the public class types in the package impl_a and similarly com.company.product.impl_b exported only to third.module .

+4
source

Source: https://habr.com/ru/post/1273461/


All Articles