为什么SWING总是强迫我将某些特定对象标记为最终?因为这有时会使事情变得有点困难,有没有办法避免这种情况?
(INCOMPLETE EXAMPLE)强制我将IExchangeSource变量标记为final:
public class MainFrame {
private final JTextArea textArea = new JTextArea();
public static void main(final IExchangeSource s) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new MainFrame(s);
}
});
}
public MainFrame(final IExchangeSource s) {
//build gui
s.update();
答案 0 :(得分:18)
这与
Swing示例:
public MyConstructor() {
final int localIntVar = 3; // this must be final
myJButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// because you use the local variable inside of an anon inner class
// not because this is a Swing application
System.out.println("localIntVar is " + localIntVar);
}
});
}
和非Swing示例:
public void myMethod() {
final String foo = "Hello"; // again it must be final if used in
// an anon inner class
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(foo);
try {
Thread.sleep(1000);
} catch (Exception e) {}
}
}
}).start();
}
有几种技巧可以避免这种情况:
编辑2 安东尼Accioly发布了一个很好的链接答案,但由于不明原因删除了他的答案。我想在这里发布他的链接,但很想看到他重新打开他的答案。
Cannot refer to a non-final variable inside an inner class defined in a different method