【发布时间】:2013-07-22 19:19:22
【问题描述】:
此代码会导致运行时错误吗? (使用了一些 android 库,但我不认为这是特定于平台的)
class A
{
Context sContext;
public A()
{
//initialize sContext here
}
public static Conext getContext()
{
return sContext;
}
}
class B
{
public static Context anotherContext;
static
{
anotherContext = A.getContext();
}
}
令人困惑的部分是在使用 eclipse 调试器时,
A.getContext()
计算为非空值。
然而
anotherContext
计算为空
有人对这种行为有任何想法吗? 谢谢
编辑:
我的错,sContext 是一个静态变量,但它只在实例方法中被赋值,就像在
public void onCreate()
{
sContext = getApplicationContext();
}
那么在这种情况下,行为会是什么?
【问题讨论】:
-
不,它不会导致运行时错误。据我所知,它甚至不会编译。你试过了吗?
-
error: non-static variable sContext cannot be referenced from a static context