JDK9模块如何帮助“封装范围的子包”? [英] How will JDK9 modules help for 'package-scoped sub-packages'?

查看:145
本文介绍了JDK9模块如何帮助“封装范围的子包”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道JDK9模块。假设您有以下3个套餐:

I am wondering about JDK9 modules. Say you have the following 3 packages:

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

包中的类 product.impl_a product.impl_b 只能通过包 product 中的类访问。用户应该只使用 product 包中的类。您可以想象,传递某些标志或属性将决定是否在内部使用 impl_a impl_b

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

在JDK8-中,您必须在 impl_a impl_b public 。这种很糟糕,因为可以欺骗用户他们可以使用这些类。它完全有效且允许。

In JDK8-, you have to make these classes inside impl_a and impl_b public. This kinda sucks, because users can be tricked that they can use these classes. It's perfectly valid and allowed.

JDK9如何在这里提供帮助?我们是否会为 product.impl_a 声明一个模块,为 product.impl_b 声明另一个模块,并声明导出的类只是由第三个模块 product 访问,这取决于两个模块 product.impl_a product.impl_b ?此外,实际上不可能声明一个新模块,它依赖于 product.impl_a product.impl_b ?其他模块是否只能依赖模块产品

How can JDK9 help here? Will we declare a module for product.impl_a and another one for product.impl_b and declare that the exported classes are only to be accessed by a third module product, which will depend on the two modules product.impl_a and product.impl_b? In addition, it will be effectively impossible to declare a new module which will depend on product.impl_a or product.impl_b? Can other modules only depend on module product?

推荐答案

问题似乎表明这三个包需要最终在不同的JAR /模块中。如果他们不这样做,只需将它们放入同一个JAR中,使用所述的可见性修饰符,并使用以下模块声明:

Nothing in your question seems to indicate that these three packages need to end up in different JARs/modules. If they don't, simply put them into the same JAR, use the visibility modifiers as described, and use the following module declaration:

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

然后 模块 com.company中的 .product 您可以像往常一样使用所有包中的代码,但仅从外部 com.company.product access

Then within module com.company.product you can use code from all packages as you normally would, but from outside only com.company.product is accessible.

这篇关于JDK9模块如何帮助“封装范围的子包”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆