Android and general pattern

I recently discovered the following pattern in Android (Intent) classes:

AClass c = data.getParcelableExtra("name");

      

Signature:

public <T extends Parcelable> T getParcelableExtra(String name)

      

Further along the path is the actor:

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 translation in the getParcelableExtra code call amazed me. I found a structure "like" findViewById (int id). Why is 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 did the casting inside the android structure in one case and not the other?

+3


source to share


1 answer


This is probably due to historical reasons: these pieces of code are not being written at the same time, not the same factors that are weighed in when choosing a style, etc.

Yesterday at Google I / O 2017 they announced that View.findViewById in Android O api will be declared as public <T extends View> findViewById(int id)

.



As seen here :enter image description here

+4


source







All Articles