Variable 'test' is accessed from within inner class, needs to be final or effectively final
时间: 2023-10-12 19:00:42 浏览: 206
member name cannot be accessed(解决方案).md
回答: 这个错误提示是因为在内部类中访问了一个局部变量test,但该变量没有被声明为final或者是effective final。在Java 8之前,如果想在匿名类中访问局部变量,必须显式地将其声明为final。例如,在Java 7中,以下代码是无法编译通过的:
```
public void demo() {
String test = "example";
foo(new Supplier<String>() {
@Override
public String get() {
return test; // 编译报错 Variable 'test' is accessed from within inner class, needs to be declared final
}
});
}
private void foo(Supplier<String> supplier) {
System.out.println(supplier.get());
}
```
但是从Java 8开始,引入了effectively final的概念,即在匿名类或Lambda表达式中访问的局部变量,如果不是final类型的话,编译器会自动加上final修饰符。因此,即使没有显式声明为final,代码也可以编译通过。所以,对于你提到的error提示,可以通过将变量test声明为final或者是effectively final来解决问题。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [Variable used in lambda expression should be final or effectively final](https://blog.csdn.net/LiZhen314/article/details/122433184)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [lambda表达式内变量为final 报错:Variable used in lambda expression should be final or effectively ...](https://blog.csdn.net/ranran0224/article/details/111686669)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [undefined](undefined)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文