Oracle的CustomDialog的Java教程代码示例的构造函数中泄漏'this'.java



首先,一些上下文。经过 2 年的休息,我刚刚回到 Java,我几乎完全用 Python 编写脚本。不幸的是,我比我想象的要生疏得多。作为复习,我一直在为我不久前编写的一个简单的程序构建一个GUI,我每天都在工作中使用。我一直在使用Oracle网站上的许多教程和示例代码来帮助填补我对Java记忆中的空白。现在,我正在创建一个可以接受、验证和返回用户输入的自定义对话框类。我在 Oracle 站点上使用此示例代码作为我的起点。大多数代码都非常有帮助,但我忍不住注意到该类的构造函数中存在this泄漏,这对于 Oracle 提供的示例代码来说似乎很奇怪。(下面的代码(

/** Creates the reusable dialog. */
public CustomDialog(Frame aFrame, String aWord, DialogDemo parent) {
super(aFrame, true);
dd = parent;
magicWord = aWord.toUpperCase();
setTitle("Quiz");
textField = new JTextField(10);
//Create an array of the text and components to be displayed.
String msgString1 = "What was Dr. SEUSS's real last name?";
String msgString2 = "(The answer is "" + magicWord
+ "".)";
Object[] array = {msgString1, msgString2, textField};
//Create an array specifying the number of dialog buttons
//and their text.
Object[] options = {btnString1, btnString2};
//Create the JOptionPane.
optionPane = new JOptionPane(array,
JOptionPane.QUESTION_MESSAGE,
JOptionPane.YES_NO_OPTION,
null,
options,
options[0]);
//Make this dialog display it.
setContentPane(optionPane);
//Handle window closing correctly.
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
/*
* Instead of directly closing the window,
* we're going to change the JOptionPane's
* value property.
*/
optionPane.setValue(new Integer(
JOptionPane.CLOSED_OPTION));
}
});
//Ensure the text field always gets the first focus.
addComponentListener(new ComponentAdapter() {
public void componentShown(ComponentEvent ce) {
textField.requestFocusInWindow();
}
});
**//Register an event handler that puts the text into the option pane.
textField.addActionListener(this);
//Register an event handler that reacts to option pane state changes.
optionPane.addPropertyChangeListener(this);**
}

我承认,我最初并不知道 NetBeans 中的"在构造函数中泄漏此内容"警告是什么意思,但此后我读到了这个问题,这个问题很有帮助;但是,我仍然不确定如何以其他方式注册这些事件处理程序。我并不关心泄漏this可能对我的程序造成的实际后果,但我想知道是否有另一种方法可以解决这个问题。考虑到它是在Oracle Java教程的示例代码中以这种方式完成的,这使我相信没有其他明显的方法可以做到这一点。

注意:我的问题不是"为什么在构造函数中泄漏this不好的做法",也不是"在构造函数中泄漏this的后果是什么"。我也不是在问为什么我的IDE(NetBeans(给我这个警告。我的问题更关心在类本身注册事件处理程序的替代方法是什么而不会泄漏this

正如你前面提到的帖子中所建议的,你可以引入一个静态创建方法,使构造函数私有,并将addXxxListener((调用移动到静态方法。

但是我会保持代码原样,也许带有@SuppressWarnings注释和警告注释,即addXxxListener()调用应保留在构造函数的末尾。

毕竟,这是一个潜在问题的警告,编译器缺乏智能来查看实例在这一点上完全完成(至少,在单线程意义上 - 多线程安全是一个不同的问题(,所有其他类过早地看到对象将有效地看到完成的版本。

最新更新