java中的包级保护有什么用? [英] What is the use of package level protection in java?

查看:127
本文介绍了java中的包级保护有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道java中的包级别保护是如何工作的。我读取很多代码(包括很多开源代码),似乎没有人使用它。整个保护级别对我来说似乎有点不对(我在一周的任何一天都有c#内部)。

I know how package level protection in java works. I read a lot of code (including lots of open source stuff) and no-one seem to be using it. The whole protection level seems slightly faulty to me (I'd have c#'s internal any day of the week).

是否存在常用的合法现实使用案例?

Are there any legit real-world use-cases that are in common use ?

编辑:一点点在提出这个问题之后我才意识到我已经忘记排除包受保护的实现类的标准模式,可能提供公共接口的实现。每个人都使用这些,正如回复中多次提到的那样。我仍然认为这个问题有很多很好的回复。

A little too late after asking this question I realized I'd forgotten to exclude the "standard" pattern of package protected implementation classes, possibly providing implementations of public interfaces. Everyone uses those, as has been noted several times in the replies. I still think there are a large number of nice replies to this question.

推荐答案

包级别可见性有两个很好的用途(根据我的经验):

There are two good uses for package level visibility (in my experience):

1)在公共API中定义内部类。通常,您将接口和核心工厂定义为公共,将内部实现定义为包级别。然后,公共工厂可以构造包级实现类,并将它们作为公共接口的实例返回。这很好地允许用户只访问他们应该的东西。

1) Defining "internal" classes in a public API. Commonly you would define your interfaces and core factories as public and the "internal" implementations as package level. Then the public factories can construct the package level implementation classes and return them as instances of the public interfaces. This nicely allows users to only access the stuff they should.

缺点是你必须将所有这些东西放在同一个包中,对于任何合理大小的API来说几乎都不是一个好主意。 JSR 294 / modules / Project Jigsaw 有望通过指定可用于的新的可见性修饰符(模块)来提供替代方案。跨模块访问模块中的类,而不会使它们在模块外部可见。你可以找到一个如何工作的例子在本文中

The downside is that you have to have all this stuff in the same package, which almost never is a good idea for any reasonably-sized API. JSR 294/modules/Project Jigsaw in Java 7 will hopefully provide an alternative by specifying a new visibility modifier (module) that can be used to access classes within a module across packages without making them visible outside the module. You can find an example of how this would work in this article.

2)单元测试是另一个常见用例。通常你会看到一个src树和一个测试树,否则它们是私有的东西而不是包级别,这样在同一个(并行)包中的单元测试能够访问其他隐藏的方法来检查或操纵状态。

2) Unit testing is the other common use case. Frequently you'll see a src tree and a test tree and stuff that would otherwise be private is instead package level so that unit tests in the same (parallel) package are able to access otherwise hidden methods to check or manipulate state.

这篇关于java中的包级保护有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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