Hiding classes in a jar file

前端 未结 8 1613
渐次进展
渐次进展 2020-12-06 02:20

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

8条回答
  •  长情又很酷
    2020-12-06 02:57

    If I understand your question correctly, you would like to make sure that users of your library are forced to use your factory to instantiate their objects rather than using the constructors themselves.

    As I see it there are two possibilities, one of which is silly but usable in few, specific cases, and the other one is the most practical and probably most commonly used way of doing it.

    1. You could make all your classes into private inner classes of the factory. This would work if you had one factory per class, but is hardly workable if you have a lot of different classes being managed through one factory.
    2. You could use the protected access modifier to restrict access to your class constructors. This is common practice when using the factory pattern.

提交回复
热议问题