【问题标题】:can I call instance method of a static member from within static context?我可以从静态上下文中调用静态成员的实例方法吗?
【发布时间】:2013-08-24 22:04:20
【问题描述】:

我有以下代码:

private static AppWidgetService mInstance = null;

public static void startRefresh() {

        AppWidgetProvider.setRefreshingState(mInstance
                .getApplicationContext());
        AppWidgetManager.refreshHandler(mInstance.getApplicationContext());
    }

运行时有时会失败,有时会通过。

对于明显的异常:

cannot call a non-static method from a static context

我很困惑mInstance 是静态的,

所以它的实例方法可以从静态上下文中调用。没有?

如果有时失败怎么办?

【问题讨论】:

  • 肯定的。您可以调用 AppWidgetService 的静态或非静态方法,但方法 'setRefreshingState()' 和 'refreshHandler()' 是静态的。因此,要么从方法头中删除静态,要么使用这些类的实例调用这些方法。
  • 我不明白。 startRefresh 是静态的,因此它可以调用同样是静态的 setRefreshingState()' 和 'refreshHandler()'。为什么建议So either you remove static from your method header or call these methods using instances of these classes.
  • 您确定拨打startRefresh 有问题吗?那些应该没问题。但是,您的 mInstance 变量可能未初始化?

标签: java android eclipse static


【解决方案1】:

从静态函数中,您可以只调用静态函数或使用静态变量。链接在运行时完成。所以,虽然你的编译会很好,但在运行时它会在调用时失败。如果您想进行该调用,请尝试使您的函数非静态。

从静态方法调用非静态方法的唯一方法是拥有一个包含非静态方法的类的实例。根据定义,非静态方法是在某个类的实例上调用的方法,而静态方法属于该类本身。

【讨论】:

【解决方案2】:

当您从非静态块/方法调用静态方法时会出现此问题。在您的代码中,“setRefreshingState()”和“refreshHandler()”都是静态方法。要调用这些方法,您必须从方法定义中删除静态。

【讨论】:

猜你喜欢
  • 2018-09-03
  • 1970-01-01
  • 2014-07-28
  • 2016-11-10
  • 1970-01-01
  • 2010-09-24
  • 2016-01-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多