我最近在 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结构的一个案例中将强制类型转换设为内部式而在另一个案例中没有这样做?