Leaking this in constructor

て烟熏妆下的殇ゞ 提交于 2019-12-23 02:54:36

问题


The Controller class is a singleton, which seems to be a special case allowing for safely passing this to Controller.

Netbeans gives

Configure "passing suspicious parameters in the constructor" hint

for controller.addObserver(this); which makes me ask what the better technique would be, although I gather it's not a good approach.

package net.bounceme.dur.usenet.swing;

import java.util.Observable;
import java.util.Observer;
import java.util.logging.Logger;
import javax.mail.Folder;
import javax.swing.ListModel;
import net.bounceme.dur.usenet.controller.Controller;
import net.bounceme.dur.usenet.controller.MessageBean;
import net.bounceme.dur.usenet.controller.MessagesDefaultListModel;

public class MessageSelect extends javax.swing.JPanel implements Observer {

    private static final Logger LOG = Logger.getLogger(MessageSelect.class.getName());
    private Controller controller = Controller.getInstance();
    private ListModel messages = new MessagesDefaultListModel();
    private MessageBean messageBean = new MessageBean();

    @SuppressWarnings("unchecked")
    public MessageSelect() {
        controller.addObserver(this);
        initComponents();
        messagesJList.setPrototypeCellValue("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
    }

回答1:


You are passing this to an external class (Controller) when the object hasn't been fully constructed. Controller could then reference your object while its construction hasn't finished.

Most people work around this by using a factory method which creates the object first, then passes this externally.

// private to force clients to use the static factory method
private MessageSelect() {
  initComponents();
  messagesJList.setPrototypeCellValue("xxx");
}

public static MessageSelect createInstance() {
  MessageSelect instance = new MessageSelect();
  instance.controller.addObserver(instance);
  return instance;
}

Take a look at this excellent Brian Goetz article on safe object construction.




回答2:


Using this as parameter can be dangerous in the contructor because the object is not fully initialized

As from http://wiki.netbeans.org/Java_Hints

I guess the point is, the super class may try and access apart of the class which has not yet been intialised (or you later change during your own construction)



来源:https://stackoverflow.com/questions/11662858/leaking-this-in-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!