patternjavaMinor
Static variable Current in Application
Viewed 0 times
currentvariablestaticapplication
Problem
I was finding myself frequently calling
Are there any pitfalls to taking this approach?
Below is, I think, the normal approach for getting the application and calling the method.
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();
}
}Solution
With this solution there is a danger that somebody accidentally change
I'd override the
According to the Code Conventions for the Java Programming Language,
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.Code Snippets
@Override
public MyApplication getApplication() {
return (MyApplication) super.getApplication();
}Context
StackExchange Code Review Q#8353, answer score: 3
Revisions (0)
No revisions yet.