方法局部内部类不能使用方法内声明的变量 [英] method-local inner class cannot use variables declared within the method

查看:226
本文介绍了方法局部内部类不能使用方法内声明的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么局部于方法内部的类不能使用在封闭方法内部声明的变量,除了标记为final的那些变量外,我知道在内部类实例保持有效的同时,在封闭方法内部声明的变量可能会消失,但是当这个变量声明为最终变量?

Why a method-local inner class can't use variables declared inside the enclosing method except those marked final, i know that the variables declared inside the enclosing method might vanishes while the inner class instance remains valid, but what has changed when this variable/s is declared final?

推荐答案

原因是它是在

使用但未在内部类中声明的任何局部变量,形式参数或异常参数必须声明为final.

Any local variable, formal parameter, or exception parameter used but not declared in an inner class must be declared final.

还要注意,项目lambda(java 8)旨在引入java中的闭包(以替换匿名类),引入了有效final的概念,该概念将允许您在lambda表达式中使用非final变量,只要您无需在闭包内进行修改.

Also note that project lambda (java 8), which aims at introducing closures in java (to replace anonymous classes), introduces the notion of effectively final which will allow you to use a non final variable within a lambda expression as long as you don't modify it within the closure.

这篇关于方法局部内部类不能使用方法内声明的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆