java - 如何访问匿名类中的局部变量?
问题描述
interface Interf {
void m1();
}
public class Test {
int x = 888;
Interf f;
public void m2() {
Integer x = 777;
f = new Interf() {
Integer x = 666;
public void m1() {
int x = 555;
System.out.println(x);
System.out.println(this.x);
}
};
}
public static void main(String[] args) {
Test t = new Test();
t.m2();
t.f.m1();
}
}
如何在具有相同名称的m1()方法(在匿名类中)中访问值为777的x 变量?是否可以访问?
解决方案
不,因为它被遮蔽了。但是您可以更改名称(不需要Integer
,int
就足够了)。
public void m2() {
int y = 777;
f = new Interf() {
int x = 666;
public void m1() {
int x = 555;
System.out.println(x);
System.out.println(this.x);
System.out.println(y);
}
};
}
输出
555
666
777
推荐阅读
- terraform - terraform 资源 i/p 参数 可能值
- python - 在 unicode 中选择字符范围
- c# - 在 VS 上用 C# 读写希伯来语字符串
- objective-c - 从 Objective-C 轻量级泛型类继承的 Swift 类在 Objective-C 代码中不可见
- delphi - FMX FormVirtualKeyboardShown 显示 Kboard 的边界不正确
- django - 将值从 django 视图传递到同一模板
- java - Spring Batch:对枚举进行分块并将其传递给阅读器
- python - 无法使用python解析网页
- wpf - WPF 路径周围不需要的边距
- python - python中的函数/循环从列表中查找数字