Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 483
Pinski Avatar asked Jul 21 '15 22:07

Pinski


People also ask

Can we access private class outside the package in Java?

You can access the private methods of a class using java reflection package.

Can we access private member outside the package?

No you cannot, by any means access the private variables in java. You can provide public getter and setter methods to access or change the value of the private member variables.

Can a class declared as private be access outside its package?

Can a class declared as private be accessed outside it's package? Not possible.


2 Answers

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.

like image 115
Krumelur Avatar answered Oct 10 '22 01:10

Krumelur


You can place your test into the same package name at another place. This is treated as the same package and you can access the package private classes. The test classes can be placed in another JAR file like testSomething.jar while the tested package is part on something.jar.

This does not work with sealed packages.

like image 29
Konrad Avatar answered Oct 10 '22 01:10

Konrad