Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android and generic pattern

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?

like image 753
Adam Avatar asked Mar 13 '26 10:03

Adam


1 Answers

This is probably due to historical reasons, these pieces of code not being written at the same time, not the same factors weighing in when deciding the style, etc.

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

As seen here:enter image description here

like image 99
Tim Avatar answered Mar 14 '26 23:03

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!