無名インナークラスからメソッドローカル変数を扱う際の制限

メモ。

	private void withErrorHandling(Block block) {
		try {
			block.call();
		} catch (Exception e) {
			System.out.println(e);
		}
	}
	
	public void doSomething() {
		// インナークラスからメソッドローカル変数 n を参照する場合、n はfinalでなければならない
		final int n = 10;
		
		withErrorHandling(new Block() {
			public void call() {
				int result = n / 2;
				System.out.println(result);
			}
		});		
		
		withErrorHandling(new Block() {
			public void call() {
				int result = n / 0;
				System.out.println(result);
			}
		});
	}

	public void doSomething2() {
		final int n = 10;
		int result = 0;
		
		withErrorHandling(new Block() {
			public void call() {
				// コンパイルエラー。メソッドローカル変数 result への代入は不可
				result = n / 2; 
			}
		});		
		System.out.println(result);
		
		withErrorHandling(new Block() {
			public void call() {
				// コンパイルエラー。メソッドローカル変数 result への代入は不可
				result = n / 0; // error
			}
		});
		System.out.println(result);
	}