Android和通用模式

时间:2017-05-18 08:48:38

标签: android generics

我最近在android类(Intent)中发现了以下模式:

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

签名:

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

还有一个演员:

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;
    }
}

调用getParcelableExtra的代码中没有强制转换让我感到震惊。我发现结构类似于&#39; findViewById(int id)。为什么findViewById没有使用以下签名实现:

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);

我没有问题,我只是想了解为什么他们在一个案例而不是另一个案例中在android结构中制作了内部演员?

1 个答案:

答案 0 :(得分:4)

这可能是由于历史原因,这些代码不是同时写的,而是在决定风格时没有相同的因素,等等。

昨天在Google I / O 2017上,他们宣布Android O api中的View.findViewById将被声明为public <T extends View> findViewById(int id)

hereenter image description here