How to organize Java-Project without packages?

241 Views Asked by At

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.

Is there any way to some how organize these java-files into "packages" without violating the information-hiding-principle?

1

There are 1 best solutions below

0
On

That is what Java 9 modules are for. They introduce an additional level of encapsulation.

private
package-private
module-private
public

module-private are public members in packages which are not exported.

In the following example, class PublicClass is in 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. 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
    }
}