安卓和通用模式

3

我最近在 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的类型转换。我发现这种结构类似于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个回答

4
这可能是由于历史原因,这些代码片段不是同时编写的,决定样式时没有考虑相同的因素等等。
在Google I/O 2017上,他们宣布Android O API中的View.findViewById将被声明为public <T extends View> findViewById(int id)
如图所示:here:enter image description here

当然知道这些因素会很好!他提到丑陋是他们将其更改为“弃儿”的原因,这非常公正。对我来说,这种构造有点不像Java风格。但他们正在改变这一点仍然非常有趣! - Adam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接