且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

访问内部类的局部变量需要声明为final

更新时间:2022-05-21 02:50:23

匿名内部类可以通过幕后的技巧访问局部变量.局部变量被实现为内部类的隐藏成员变量.它们被分配了局部变量的副本.为了防止复制值出错,Java 编译器强制这些局部变量必须是 final 以便它们不会被更改,因此副本保持正确.

Anonymous inner classes have access to local variables through a trick behind the scenes. Local variable are implemented as hidden member variables of the inner class. They are assigned copies of the local variable. To prevent the copy value from being wrong, the Java compiler enforces that these local variables must be final so they aren't changed, so the copy stays correct.

封闭类的字段不需要是final;使用的局部变量必须是 final.您必须使匿名内部类中使用的所有局部变量final.你可以通过声明 final 变量来初始化你的 ij 值,并在你的匿名内部类中使用它们.>

The fields of the enclosing class don't need to be final; the local variables used must be final. You must make all local variables used in your anonymous inner class final. You can do this by declaring final variables to be initialized to your i and j values, and use them in your anonymous inner class.

// Inside the for loops in the createGrids method
grids[i][j] = new JButton();
// Declare x, y final
final int x = i;
final int y = j;
grids[i][j].addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){ 
        // Use x, y instead of i, j inside.
        if (squares[x][y] == 1)
        {
             System.out.println("BOmb");
        }
        else {
             grids[x][y].setVisible(false);
        }
    }
 });

请注意,在 Java 8 中,这不是必需的,因为 Java 8 编译器可以检测匿名内部类中使用的局部变量是否有效最终",即不是 final 而是初始化后永不改变.

Note that in Java 8, this would not be necessary, because the Java 8 compiler can detect if the local variables used in anonymous inner classes are "effectively final", that is, not final but never changed once initialized.