简体   繁体   English

如何在没有包的情况下组织 Java 项目?

[英]How to organize Java-Project without packages?

I am working on a java-library and due to information-hiding, I was forced to move all my java-files into a single package in order to mark some of them as package private.我正在研究一个 java 库,由于信息隐藏,我被迫将所有 java 文件移动到一个 package 中,以便将其中一些标记为 package 私有。

Is there any way to some how organize these java-files into "packages" without violating the information-hiding-principle?有什么办法可以在不违反信息隐藏原则的情况下将这些 java 文件组织成“包”?

That is what Java 9 modules are for.这就是 Java 9模块的用途。 They introduce an additional level of encapsulation.它们引入了额外的封装级别。

private
package-private
module-private
public

module-private are public members in packages which are not exported. module-private是未导出的包中的公共成员。

In the following example, class PublicClass is in package com.library .在以下示例中,class PublicClass位于 package com.library In that same package, there is a module-info.java file which declares a Java module and exports packages which are public API. In that same package, there is a module-info.java file which declares a Java module and exports packages which are public API. All classes in the packages which are not exported will not be visible from modules which depend on this one.未导出的包中的所有类都不会从依赖于该类的模块中可见。

package com.library;

public class PublicClass {}
package com.library.internal;

public class InternalClass {}
module com.library {
    exports com.library;
}
module com.app {
    requires com.library;
}
package com.app;

class App {
    void run() {
        new InternalClass(); // compile-time error
        new PublicClass(); // success
    }
}

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

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