Java 对方法中声明的内部类中变量的可见性有一些疑问
我对该方法的工作原理有以下疑问:Java 对方法中声明的内部类中变量的可见性有一些疑问,java,actionlistener,inner-classes,Java,Actionlistener,Inner Classes,我对该方法的工作原理有以下疑问: protected JButton createToolbarButton(String name, final String id, final JPanel panel) { JButton button = new JButton(name); // Create a new JButton // If the passed Jpanel named "panel" exist, add this to the JPanel
protected JButton createToolbarButton(String name, final String id, final JPanel panel)
{
JButton button = new JButton(name); // Create a new JButton
// If the passed Jpanel named "panel" exist, add this to the JPanel named content (the CardLayout container)
if (panel != null)
content.add(panel, id);
else
button.setEnabled(false); // Otherwise disable this button
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
//System.out.println(panel.getClass());
if (panel instanceof SchedulingPanel)
((SchedulingPanel)panel).getTasksSettings().fireSettingsUpdated();
else if (panel instanceof EventsPanel)
((EventsPanel)panel).refreshPanel();
else if (panel instanceof ConfigurationPanel)
((ConfigurationPanel)panel).refreshPane();
showSection(id);
}
});
return button;
}
我有一个名为CreateToolbarButton的方法,它有一些输入参数,包括字符串id参数
正如您在这个方法中所看到的,我向我的JButton对象(处理这个按钮上的点击事件)添加了一个ActionListener内部类
在这个ActionListener内部类中声明了处理点击事件的actionPerformed()方法,并在这个方法的末尾调用showSection(id)方法,将id参数传递给id,该参数似乎与CreateTorbarButton()相同输入参数
因此,在我看来,在我的ActionListener内部类中,我还可以看到容器方法的参数和变量(createToolbarButton())
是这样吗?为什么?我觉得有点奇怪
Tnx
安德里亚是的,你确实有能见度。这些变量是最终变量,这一事实就保证了这一点。换句话说,由于它们没有改变,内部类不会尝试引用一个在方法createToolbarButton完成时可能死亡的变量 如果您认为这种行为很奇怪,并且不希望出现这种情况,那么不要使用内部类。改用普通的一级类 在我看来,在我的
ActionListener
内部类中,我还可以看到容器方法(createToolbarButton()
)的参数和变量,对吗
绝对-您可以看到传递给方法的所有局部变量和参数,只要声明它们final
(与您一样)
为什么??我觉得有点奇怪
这是匿名类没有构造函数的设计结果。这种隐式捕获局部变量和参数的能力使您可以编写不需要匿名类就可以拥有构造函数的代码
但实际上,您的匿名类确实有一个构造函数。由于从方法实现体引用它们而需要捕获的所有
final
局部变量都将成为此不可见构造函数的参数。编译器隐式地传递这些参数,以及对封闭类的this
的引用,然后在引用它们的方法体中插入对这些捕获属性的引用。是的,final
变量在匿名内部类中可见。请参阅的可能重复项