Android与泛型模式

Android与泛型模式,android,generics,Android,Generics,我最近在android类中发现了以下模式(Intent): 签名: public <T extends Parcelable> T getParcelableExtra(String name) public <T extends View> T genericsFindViewById(int id) { switch (id){ //Bogus method body as example case 1: return

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

签名:

public <T extends Parcelable> T getParcelableExtra(String name)
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);
public T getParcelableExtra(字符串名称)
沿着小路往下走,有一个演员阵容:

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;
    }
}
public T getParcelable(字符串键){
unparcel();
对象o=mMap.get(键);
如果(o==null){
返回null;
}
试一试{
返回(T)o;
}catch(ClassCastException e){
类型警告(键,o,“可包裹”,e);
返回null;
}
}
调用getParcelableExtra的代码中缺少强制转换,这让我感到震惊。我发现这个结构“类似于”findViewById(intid)。为什么findViewById没有使用以下签名实现:

public <T extends Parcelable> T getParcelableExtra(String name)
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);
public T genericsFindViewById(int-id){
开关(id){//以伪方法体为例
案例1:
返回(T)新的文本视图(getActivity());
案例2:
返回(T)新的RecyclerView(getActivity());
违约:
返回(T)新的ImageView(getActivity());
}
}
//例子
TextView t=genericsfindviewbyd(1);
RecyclerView r=通用FindViewById(2);
ImageView i=通用FindViewById(4);
TextView t2=genericsfindviewbyd(4);//这给了ClassCastException
//但以下内容也同样适用:
TextView t3=(TextView)rootView.findviewbyd(R.id.image\u视图);

我没有问题,我只是想了解为什么他们在一种情况下在android结构中进行内部转换,而不是在另一种情况下进行内部转换?

这可能是由于历史原因,这些代码没有同时编写,在决定样式时没有考虑相同的因素,等等

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


如图所示:

当然很高兴知道这些因素是什么!他提到丑陋是他们将其改为“抛弃者”的原因,这是非常公平的。对我来说,这感觉有点像一个非java的结构。仍然很有趣,他们正在改变它!