问题描述
给定一个相对简单的类
class TestNull {
static void main(String [] a) {
Long whatever = 1
// this works
new Runnable() {
void run() { println(whatever) }
}.run()
// this doesn't
new Weird() {
@Override
void x() { println(whatever) } // NPE
}
}
static abstract class Weird {
Weird() { x() }
abstract void x();
}
}
在构造扩展 main()
的匿名类期间,执行 whatever
会引发 NPE 尝试访问 Weird
。相同的代码在 Java 中运行良好,只要在构造类之后访问变量,它也可以正常运行(因此是匿名 Runnable
的示例)。
我想知道这里发生了什么,这是一个 Groovy 错误(我正在使用 3.0.5 进行测试),或者它应该是那样的。但是我不确定在这种情况下 null
到底是什么,你如何从逻辑上解释从匿名类访问外部作用域变量的规则......
NPE:
Exception in thread "main" java.lang.NullPointerException
at org.example.TestNull$2.x(TestNull.groovy:15)
at org.example.TestNull$Weird.<init>(TestNull.groovy:20)
at org.example.TestNull$2.<init>(TestNull.groovy)
at org.example.TestNull.main(TestNull.groovy:13)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)