I recently discovered the following pattern in android classes (Intent):
AClass c = data.getParcelableExtra("name");
signature:
public <T extends Parcelable> T getParcelableExtra(String name)
Further down the trail there is a cast:
public <T extends Parcelable> T getParcelable(String key) {
unparcel();
Object o = mMap.get(key);
if (o == null) {
return null;
}
try {
return (T) o;
} catch (ClassCastException e) {
typeWarning(key, o, "Parcelable", e);
return null;
}
}
The lack of a cast in the code calling getParcelableExtra struck me. I found the structure 'similar to' findViewById(int id). Why are findViewById not implemented with the following signature:
public <T extends View> T genericsFindViewById(int id) {
switch (id){ //Bogus method body as example
case 1:
return (T) new TextView(getActivity());
case 2:
return (T) new RecyclerView(getActivity());
default:
return (T) new ImageView(getActivity());
}
}
//Examples
TextView t = genericsFindViewById(1);
RecyclerView r = genericsFindViewById(2);
ImageView i = genericsFindViewById(4);
TextView t2 = genericsFindViewById(4); // this gives ClassCastException
//But the following would as well:
TextView t3 = (TextView) rootView.findViewById(R.id.image_view);
I have no problem, I just want to understand why they made the cast internal in the android structure in one case and not the other?