EventActionDispatcher 可以发布“this”吗? 在构造函数完成之前?
使用 EventActionDispatcher 的推荐方法如下(根据 API 文档 @ http://struts.apache.org/1.2.9/api/org/apache/struts/actions/EventActionDispatcher.html )
public class MyCustomAction extends Action {
protected ActionDispatcher dispatcher = new EventActionDispatcher(this);
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
return dispatcher.execute(mapping, form, request, response);
}
}
这样做是否会在构造函数退出? 管理方法之外的字段分配的规则是什么。
提前致谢。
真挚地, 莱斯
The recommended way to use the EventActionDispatcher is as follows (per the API docs @ http://struts.apache.org/1.2.9/api/org/apache/struts/actions/EventActionDispatcher.html )
public class MyCustomAction extends Action {
protected ActionDispatcher dispatcher = new EventActionDispatcher(this);
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
return dispatcher.execute(mapping, form, request, response);
}
}
Does doing this publish the reference to "this" before the constructor exits? What are the rules governing field assignments outside of methods.
Thanks in advance.
Sincerely,
LES
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
每周需要 3 个人追踪一次……如果 EventActionDispatcher 启动一个线程或对线程执行任何导致使用“this”的操作,“this”可能为 null。
永远不要在构造函数完成之前传递“this”,否则在线程情况下您将面临“this”为 null 的风险。
我所做的是将“init()”方法添加到需要执行类似操作的类中,并在创建对象后调用它。
还有其他微妙之处,例如这个例子:
最安全的做法是:
您可以调用最终方法,但您必须确保它们不会调用可重写的方法...这可能意味着事情会崩溃...所以不这样做更安全。
That took 3 people a week to track down once... "this" can be null if the EventActionDispatcher starts a thread or does anything with a thread that causes the "this" to be used.
NEVER pass "this" before the constructor has completed or you run the risk of "this" being null in the case of threading.
What I do is add an "init()" method to my classes that need to do things like that and call it after I create the object.
There are also other subtleties, such as this example:
The safest thing to do is:
You can can call final methods, but you have to be sure that they do not call overrideable methods... and that can mean things break down the road... so safer not to do it.
在这种情况下(我希望)
this
不会被发布。 它仍然只能通过MyCustomAction
实例访问。在 Java 中(我相信 C# 的做法相反),实例字段初始化和实例初始化程序在(隐式或显式)调用超级构造函数之前直接调用。 因此,您可以在字段初始化中使用
this
,尽管您的对象可能尚未完成构造。发布
this
以便在构造期间可以从对象外部访问它通常是一个坏主意。In this case (I hope)
this
does not get published. It's still only reachable through theMyCustomAction
instance.In Java (I believe C# does the opposite), instance field initialisation and instance initialisers are called directly before the (implicit or explicit) call to the super constructor. Therefore you can use
this
in field initialisation, although your object may not have finished construction.Publishing
this
so it it reachable from outside the object during construction is generally a bad idea.