Static variable Current in Application I was finding myself frequently calling getApplication() and casting it as MyApplication so that I could call a method in MyApplication.  I decided to declare the static variable Current in MyApplication and set it in the constructor.  Now I don't have to do the casting.

Are there any pitfalls to taking this approach?

public class MyApplication extends Application {
    public static MyApplication Current;
    public MyApplication(){
        super();
        Current = this;
    }
    public void doSomething(){

    }
}

public class MyActivity extends ListActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.Current.doSomething();
    }
}


Below is, I think, the normal approach for getting the application and calling the method.

public class MyApplication extends Application {
    public void doSomething(){

    }
}

public class MyActivity extends ListActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ((MyApplication)getApplication()).doSomething();
    }
}
With this solution there is a danger that somebody accidentally change MyApplication.current to null or an invalid reference.

I'd override the getApplication method in the MyActivity class with a covariant return type:

@Override
public MyApplication getApplication() {
    return (MyApplication) super.getApplication();
}




According to the Code Conventions for the Java Programming Language, Current should be current.