简体   繁体   English

从外部模块使用包私有的构造函数实例化类

[英]Instantiating classes with package-private constructors from outside modules

I would like to make use of a package-private constructor, to prevent the instantiation of a certain object from the outside. 我想利用包私有的构造函数,以防止从外部实例化某个对象。 The only one who should be able to instantiate the class is a factory class, which resides in the same package. 唯一能够实例化该类的是工厂类,它位于同一包中。

My concerns are that if my application gets compiled and sealed, the only possible way to ever provide new classes with a package-private scope, which could be accessed by the same factory (or a why not a new implementation of the factory), would be to mimic the exact same path to the package in the project that references my sealed lib. 我担心的是,如果我的应用程序得到了编译和密封,那么唯一有可能提供具有包私有范围的新类的唯一方法是可以由同一工厂访问(或者为什么不使用工厂的新实现)?是模仿引用我密封的lib的项目中程序包的完全相同的路径。

Though this is by no means impossible, I am just wondering if it should be considered a good practice. 尽管这绝非不可能,但我只是想知道是否应将其视为一种良好做法。 What do you think about package-private scope used in that sense? 在这种意义上,您如何看待私有包范围?

It should work this way. 它应该以这种方式工作。 I don't have another way in mind to achieve this neither. 我也没有其他方法可以实现这一目标。

But, IMHO it is often not very constructive to do so. 但是,恕我直言,这样做通常不是很有建设性的。 There might be corner cases to prohibit other-then-expected-usage, but in general I think you should try to establish the factory because its ease of use and convince people with that. 可能会有一些极端的情况禁止其他用途,但一般来说,我认为您应该尝试建立工厂,因为它易于使用,并且可以说服人们。 If your factory is not extendable, people may end up creating classes in "your" package just to access your classes like they want. 如果您的工厂不可扩展,那么人们最终可能会在“您的”程序包中创建类,只是想按自己的意愿访问您的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM