我正在查看 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/