can I call instance method of a static member from

2019-09-21 19:43发布

I have the following code:

private static AppWidgetService mInstance = null;

public static void startRefresh() {

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

It sometimes fails in runtime, and sometimes passes.

for the obviuse exception:

cannot call a non-static method from a static context

I'm confused as mInstance is static,

so its instance methods could be called from a static context. no?

then how come if sometimes fails?

2条回答
何必那么认真
2楼-- · 2019-09-21 20:09

From a static function, you can call only static function or use static variable. The linking is done at run time. So, though your compilation will be fine but at run time it will fail when call is made. Try making your function non static if you want to make that call.

OR

The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method. By definition, a non-static method is one that is called ON an instance of some class, whereas a static method belongs to the class itself.

查看更多
一纸荒年 Trace。
3楼-- · 2019-09-21 20:18

This problem arises when you call a static method from a non-static block/method. In your code both 'setRefreshingState()' and 'refreshHandler()' are static methods. To call theses methods you have to remove static from your method definition.

查看更多
登录 后发表回答