java - 代码中的变量范围

标签 java javascript gwt

我正在查看 GWT 教程,并对这段代码感到困惑。

代码位于 GWT tutorials

private void addStock() {
        final String symbol = newSymbolTextBox.getText().toUpperCase().trim();
        newSymbolTextBox.setFocus(true);

        // Stock code must be between 1 and 10 chars that are numbers, letters,
        // or dots.
        if (!symbol.matches("^[0-9A-Z\\.]{1,10}$")) {
            Window.alert("'" + symbol + "' is not a valid symbol.");
            newSymbolTextBox.selectAll();
            return;
        }

        newSymbolTextBox.setText("");

        // Don't add the stock if it's already in the table.
        if (stocks.contains(symbol))
            return;

        // Add the stock to the table.
        int row = stocksFlexTable.getRowCount();
        stocks.add(symbol);
        stocksFlexTable.setText(row, 0, symbol);
        stocksFlexTable.setWidget(row, 2, new Label());
        stocksFlexTable.getCellFormatter().addStyleName(row, 1,
                "watchListNumericColumn");
        stocksFlexTable.getCellFormatter().addStyleName(row, 2,
                "watchListNumericColumn");
        stocksFlexTable.getCellFormatter().addStyleName(row, 3,
                "watchListRemoveColumn");

        // Add a button to remove this stock from the table.
        Button removeStockButton = new Button("x");
        removeStockButton.addStyleDependentName("remove");
        removeStockButton.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                int removedIndex = stocks.indexOf(symbol);
                stocks.remove(removedIndex);
                stocksFlexTable.removeRow(removedIndex + 1);
            }
        });
        stocksFlexTable.setWidget(row, 3, removeStockButton);

        // Get the stock price.
        refreshWatchList();
    }

问题部分是向removeStockButton添加事件处理的匿名内部类。该类的 onClick 方法接受一个事件,然后使用变量 symbol 从 ArrayList stocks 中检索要删除的行的索引。

当用户实际调用 onClick()(即单击删除按钮)时,符号如何仍在范围内?如果您怀疑代码的正确性,它来自 Google 工程师,因此是正确的(而且,它有效,我已经使用过它)。

这是 JavaScript 技巧还是我需要 Java 推荐类(class)?

最佳答案

这是因为且仅因为符号在封闭方法中被声明为final。

这里是 Java 中匿名类的简要说明的链接:see here .

关于java - 代码中的变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1517666/

相关文章:

javascript - React.js 如何在另一个组件中使用一个组件?

java - 如何获取字符串的所有子序列组合(在 Java 或 C++ 等中)

java - Hibernate Validator - 根据生命周期进行可选验证

javascript - 如何在 TypeScript 中通用类型变量绑定(bind)?

javascript - 获取子字符串直到第 n 个匹配正则表达式

java - Designer 中奇怪的 GWT 异常

java - 在包中运行所有测试时出现 JUnit java.lang.OutOfMemoryError

java - 可以使用Youtube Android V3 API控制左右声道的音量吗?

使用 FireFox 时 HTMLPane 缺少滚动条

javascript - 有没有办法在 Chrome 开发者工具中评估源映射中的变量?