The following example is taken from GWT tutorial (

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

	if (!symbol.matches("^[0-9A-Z\\.]{1,10}$")) {
		Window.alert("'" + symbol + "' is not a valid symbol.");

	if (stocks.contains(symbol)) {

	int row = stocksFlexTable.getRowCount();
	stocksFlexTable.setText(row, 0, symbol);

	Button removeStockButton = new Button("x");
	removeStockButton.addClickHandler(new ClickHandler() {
		public void onClick(ClickEvent event) {
			int removedIndex = stocks.indexOf(symbol);
	stocksFlexTable.setWidget(row, 3, removeStockButton);


I have hard time understanding this: the clickhandler of removeStockButton is getting the index of the symbol and then removes from arrayList. How is the handler know dynamically about symbol? Because symbol is a variable define in the addstock method. During compile time or when the addStock() method is entered, symbol is known. But during run time when a button is clicked and the clickhandler code is entered now how does it know symbol it independent of addStock(). It is behaving like ruby generator. How does it work? Where is the magic here?


The instance of the anonymous inner class exists only in the context of the runtime stack of the method, is a method local variable and as such has access to other method local variables of that same method instance.

The "final" keyword is essential here. The compiler knows that the value assigned to the variable can not be changed, so its value can be used in the inner class even after the method has terminated.

Edited 6 Years Ago by JamesCherrill: n/a

This article has been dead for over six months. Start a new discussion instead.