我们可以停止构造函数的运行吗?
我需要创建某种类型的对象。 对象的类只有一个构造函数(我编写的一个)。
我的程序收到创建具有参数 ID 的对象实例的请求。 如果 ID 参数包含不是数字的字符,我想停止构造函数。
我之前无法检查参数,因为我不是调用构造函数的人。
I need to create an object of some type.
The class of the object has just one constructor (one that I've written).
My program receive requests to create instances of an objects with a parameter ID.
I want to stop the constructor if the ID parameter contains a char that is not a digit.
I cannot check the parameter before, since I'm not the one who calls the constructor.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将构造函数设为私有并公开一个静态工厂方法,如果参数有效,该方法将验证并返回对象的新实例。
Make the constructor private and expose a static factory method, that will validate and return a new instance of the object if the parameter is valid.
“停止”构造函数的唯一方法是抛出异常。当然,请记住,调用者应该“知道”此异常并能够处理构造函数失败的情况。
从构造函数抛出异常并不会阻止对象的创建,它只会使其引用对变量的分配失败,并且引用不可用(因此有资格进行垃圾回收)除非您将
this
从构造函数本身传递给外部方法的错误。 (无论如何你都不应该这样做。)The only way to "stop" a constructor is to throw an exception. Bearing in mind of course that the caller is supposed to "know" about this exception and be able to handle the case where the constructor fails.
Throwing an exception from the constructor doesn't stop the object being created though, It just makes the assignment of its reference to a variable fail and the reference unavaliable (and therefore eligible for garbage collection) unless you make the mistake of passing
this
to an external method from the constructor itself. (Which you shouldn't do anyway.)如何解决这个问题取决于当给出非法字符时您希望发生什么,这又取决于我们正在讨论的对象以及使用它的库如何使用它。
最合理的做法是抛出一个
IllegalArgumentException
,这就是我建议您所做的。然而,尽管我强烈建议不要这样做,但仅
返回 null
也可能是有意义的(您不能直接在构造函数中执行此操作,但您可以创建一个工厂方法来执行此操作)这)。How to solve this depends on what you want to happen when an illegal character is given, which in turn depends on what object we're talking about, and how the consuming library is using it.
The most reasonable thing to do would be to throw an
IllegalArgumentException
, and this is what I'd suggest you do.However, it might make sense to just
return null
, too, even though I'd strongly recommend against it (you can't do this directly in the constructor, but you can create a factory method that does this).