简体   繁体   English

子包之间的Java私有类

[英]Java private classes between sub-packages

My Java library is made of a few sub-packages (com.example.lib.api, com.example.lib.imp, com.example.lib.util,...). 我的Java库由几个子包组成(com.example.lib.api,com.example.lib.imp,com.example.lib.util,...)。

The classes in api use classes A and B from imp . api的类使用imp A类和B类。 The classes in imp use class C in util . imp类在util使用C类。 I am forced to make A , B and C public, but I don't want them to be exposed to users of my library. 我被迫公开ABC ,但我不希望它们暴露给我的图书馆的用户。 Not hiding anything, my library is open source, but minimal APIs are simpler to understand. 没有隐藏任何东西,我的库是开源的,但最小的API更容易理解。

Is there a way around it? 有办法解决吗?

In Java 9 you will be able to control which packages are exported from a JAR. 在Java 9中,您将能够控制从JAR导出的包。 This way you can make them public, but not available to anyone else. 通过这种方式,您可以将其公开,但其他任何人都无法使用。

For now you can't control this. 现在你无法控制它。 You either put everything in one package or rely on the documentation to make it clear they should not be used. 您要么将所有内容放在一个包中,要么依赖文档来明确它们不应该被使用。 eg jdk.internal assumes no one should use these except the JDK. 例如, jdk.internal假设除了JDK之外没有人应该使用这些。

You cannot use a private class in any other package . 您不能在任何其他包中使用私有类。 Instead the class can be made public and the methods and variables can be made protected . 相反,可以将类公开,并且可以保护方法和变量。 So in this case the classes can be extended where they need and the contents in the class can be accessed only by the sub classes which extended it. 因此,在这种情况下,类可以在需要的地方扩展,并且类中的内容只能由扩展它的子类访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM