2017-05-18 9 views
3

私は最近、アンドロイドのクラス(テント)で、次のパターンを発見:Androidと一般的なパターン

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)に似た構造を見つけました。私はちょうど彼らが他の一つのケースにはアンドロイド構造で内部キャストしないで作られた理由を理解したい、

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

私は何の問題もない:なぜfindViewByIdは、次の署名を使用して実装されていませんか?

答えて

4

これは、彼らが発表されたGoogleのI/O 2017で

昨日など、による歴史的な理由のために、コードのこれらの作品が同時に書き込まれていない、おそらくスタイルを決定する際における計量と同じ要因ではありませんAndroid O APIのView.findViewByIdはpublic <T extends View> findViewById(int id)と宣言されます。 here見られるように

enter image description here

+0

はofcourseの要因は何であったかを知っていいだろう!彼は、彼らがそれを非常に公正な「逃亡者」に変える理由として、醜さを言います。それは私に建設のJavaのようなビットを感じる。彼らがそれを変えているということはまだ非常に興味深い! – Adam

関連する問題