Java 在构造函数中调用 setter
我正在 setter 方法中验证输入数据,并且不想在构造函数中再次验证它。我想知道在构造函数中调用 setter 是否是个好主意?
I am validating input data in setter method and don't want to validate it again in constructor. I wonder if calling the setter in the constructor is good idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从构造函数调用 setter 效果很好。促进代码重用。
Calling a setter from a constructor works just fine. Promotes code reuse.
是的,您可以在构造函数中调用setter。
这不被禁止
Yes, you can call setter in constructor.
it's not prohibited
你可以这么做。这是可能的,但我还建议您查看论坛链接。
这篇文章应该让您了解构造函数注入与 Setter 注入 链接
You can do that. It's possible, but I would also suggest you to check forum link.
This post should give you idea about Construtor Injection vs Setter Injection link
通常被认为是安全的,但需要注意以下几点:
唯一可能遇到的麻烦是 setter(或从构造函数调用的任何方法)在子类中被重写。为了绝对安全(偏执?),请确保从构造函数调用的所有方法都是最终的。
Generally considered safe, with the following caveat:
the only possible trouble you can get into is if the setter (or any method you call from a constructor) is overridden in a sub class. To be absolutely safe (paranoic?), make sure that all methods called from a constructor are final.