【发布时间】:2015-05-06 11:55:21
【问题描述】:
Java 匿名内部类允许无缝访问在外部对象的方法堆栈上声明的变量,只要它们声明为 final。
但是,如果我在内部类中声明了一个同名的变量怎么办?有没有办法显式引用外部变量?
public class Outer {
public static void main(String[] args) throws Throwable {
new Outer().call();
}
private void call() throws Throwable {
final String str = "I'm the outer String!";
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
String str = "I'm the inner String!";
// This prints the inner String
System.out.print(str);
// So, can I have explicitly access to the outer String?
}
});
}
}
顺便说一句,这与 this 问题不同,因为它涉及 本地堆栈 变量。
【问题讨论】:
-
如果您使用不同的名称作为字符串引用,它是否有效?
-
即使有一些方法可以让它工作,代码也会造成不必要的混乱和不可读。简单实用的解决方案(虽然不是您的问题的答案)是使用不同的标识符。
标签: java variables anonymous-class