We all agree that the use of instanceOf is usually not the best solution. There are plenty of examples in the web.
But lets consider for a second the following example, where we need to call a method from a fragment to its activity:
public class BaseActvity extends FragmentActivity implements ISomething {
@Override
public void doSomething();
}
Then lets say we have a fragment in the app that needs to call doSomething()
:
public MyFragment extends Fragment() {
public void onCreate() {
public void onResume() {
Activity activity = getActivity();
if (activity != null && activity instanceOf ISomething) {
ISomething something = (ISomething) activity;
something.doSomething();
}
}
}
public interface ISomething {
void doSomething();
}
As you can see, we cannot guarantee that getActivity() will return an object of ISomething, so we check the type. An improvement would be to add an interface, but we would still to check the getActvity() return type to protect our code.
Because of the nature of the Android Framework and the getActivity() call, I can't find a better solution. Maybe someone can help with some input..
NOTE: Ive added an interface to follow the visitor pattern. Notice that I still have to use instanceOf to assure that the parent activity is implementing it.
Thank you .
Gaspar de Elais