Search code examples
javac#internalpackage-private

Is there a way to use package-private in java to allow other packages access?


So I've been working in C# for a number of years and am now working in Java. In C#, you can use the internal keyword to hide a class/method from public view but allow certain assemblies/packages access if you specifically grant it. As I look around in Java I don't see anything that is directly the same as internal.

I found out about package-private. However, this keeps it completely hidden from the outside world. Is there a way in Java to allow certain other packages access to internal code without making it public?

If you are asking why I would do this answers are generally unit / integration testing or a need to have certain, trusted packages access to code as to not duplicate it. I know some people think you shouldn't test private / internal code. I also know that allowing inside access is not generally good software engineering. I'm not really interested in discussion on these topics, just curious if you can do what I want to do.

Thanks.


Solution

  • Java does not have the concept of assemblies like in .NET (at least not yet). The closest thing is OSGi bundles, which has this concept (x-internal, x-friend, etc), but that is not really core Java.

    If you are not using OSGi, there should be no need go through this complication. Just make sure your unit tests are in the same package as the class under test. The Maven directory structure (which is a good choice even if you are not using Maven) sets you up for this with src/main/java, src/test/java etc.