Valentyn Zakharenko
Valentyn Zakharenko

Reputation: 3088

How to do package-private classes visible for other one package only?

I want to implement package with optimal encapsulation, but test it. How can I do package-private members of one package visible for other one (friendly) package only?

Upvotes: 3

Views: 1837

Answers (2)

Bohemian
Bohemian

Reputation: 424993

Yes, it can be done. Kind of...

package private stuff is visible to other classes in the same package, but not necessarily the same directory.

You can declare a class as being in the same package but place it under another directory structure (eg your test code) or even within another project.

You mentioned testing, so I assume you want to "see" this stuff in your tests. Just define your test classes as being in the same package (not the same directory) as your production code.

Upvotes: 3

dave
dave

Reputation: 11975

By definition package-private members are not visible to classes outside the package. This would suggest you are trying to do something you shouldn't, even though you are testing.

You could work around it with a getter, or reflection, but I'd first look at whether you need to access such a member. If it's internal state, you shouldn't be testing it. If it's not, then a getter may be appropriate. Or put your tests in the same package (but possibly stored in a different directory tree).

Upvotes: 1

Related Questions