Hiding classes in a jar file

nrainer picture nrainer · Jan 21, 2011 · Viewed 12.9k times · Source

Is it really impossible to hide some classes in a jar file?

I wanted not to allow direct instantiation of the classes to keep it more flexible. Only the factory (or a facade) should be visible of this jar.

Is there any other way than solve this problem than creating two projects? (Two projects: the first one contains the classes (implementation) and the other one references to the first one and contains the factory; later only the second one will be referenced)

Answer

Mikko Wilkman picture Mikko Wilkman · Jan 21, 2011

I'm understanding you're not looking to hide the actual classes, just prevent their construction outside a factory class. This I think can be quite easily achieved by using package private (default) visibility in the class constructors. The only limitation is that you'll need to have the classes and the factory in the same package so in a medium to large codebase things may get unnecessarily complex.