java - 从匿名类内部访问方法范围内的变量
问题描述
如何通过x = 12
以下代码中的值打印 12,
注意我们不能更改变量名称
public class Master {
final static int x = 10;
private void display() {
final int x = 12; // How to print this in run() method
Runnable r = new Runnable() {
final int x = 15;
@Override
public void run() {
final int x = 20;
System.out.println(x); //20
System.out.println(this.x); //15
System.out.println();// What to write here to print (x = 12)
System.out.println(Master.x); //10
}
};
r.run();
}
public static void main(String[] args) {
Master m = new Master();
m.display();
}
}
任何帮助,将不胜感激。
解决方案
public class Master {
final int x = 10;
private void display() {
final int x = 12;
class RunImpl implements Runnable {
int xFromAbove;
int x = 15;
private RunImpl(int x) {
this.xFromAbove = x;
}
@Override
public void run() {
final int x = 20;
System.out.println(x); //20
System.out.println(this.x); //15
System.out.println(this.xFromAbove); //12
System.out.println(Master.this.x); //10
}
}
RunImpl r = new RunImpl(x);
r.run();
}
public static void main(String[] args) {
Master m = new Master();
m.display();
}
}
推荐阅读
- google-sheets - 下拉选择使用来自另一个选项卡的数据填充工作表
- windows - 解压多个文件到不同目录
- sql - 检索日期超过 6 个月的记录并更新同一表中的列
- excel - VBA,将前一列存储为变量时使用
- javascript - 有没有办法使用 Puppeteer 在站点中搜索多个 ID 并检查它们是否为空?
- php - 如何在没有插件的情况下为我的 wordpress 主题创建加载更多分页
- javascript - 节点中的正文解析器
- jenkins - 变量未按预期在 Jenkins 管道阶段之间的 shell 命令之间共享
- mysql - Flask-SQLAlchemy 错误 MySQL 服务器已消失
- mysql - SELECT 字符串中的时间格式