【问题标题】:using an instance variable in static block在静态块中使用实例变量
【发布时间】: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

标签: java static


【解决方案1】:

这甚至不会编译。它会给你错误

“不能从静态上下文中引用非静态变量”

因为您正试图从静态块访问实例变量,所以如果 initializer block 是非静态的或变量是 static,这将运行。

【讨论】:

    【解决方案2】:

    这行不通。 anotherContext 不是静态的,因此无法从静态方法 getContext 中检索。如果要初始化上下文,请在静态初始化块中进行。

    【讨论】:

      【解决方案3】:

      您不能从静态方法访问实例变量。请记住,静态方法不了解您的类的任何特定实例。它通常只是作为您的类的一种方法存在。换句话说,你的

      public static Conext getContext() {
          return sContext;
      }
      

      方法不知道实例sContext对象。

      【讨论】:

        猜你喜欢
        • 2021-11-29
        • 2022-09-23
        • 1970-01-01
        • 2019-03-28
        • 2015-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-07
        相关资源
        最近更新 更多