2017-12-27 133 views
0

我有這樣的BaseFragment:通用BaseFragment驗證實現的接口回調

public abstract class BaseFragment<C> extends Fragment { 

    protected C callback; 

    @Override 
    @SuppressWarnings({"unchecked"}) 
    public void onAttach(final Context context) { 
     super.onAttach(context); 
     try { 
      this.callback = (C) getActivity(); 
     } catch (final ClassCastException e) { 
      throw new ClassCastException(context.toString() + " must implement " + this.callback.getClass().getSimpleName()); 
     } 
    } 
} 

我有一個執行片段:

public class MainFragment<C extends MainFragment.Callback> extends BaseFragment<C> { 
    public static MainFragment newInstance() { 
     MainFragment<Callback> fragment = new MainFragment<>(); 
     return fragment; 
    } 

    public interface Callback { 
     void doSomething(); 
    } 

    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.fragment_main, container, false); 

     return view; 
    } 
} 

我創建一個靜態的newInstance方法的片段。 當我在onAttach中放置斷點時,它永遠不會失敗,我的活動甚至沒有實現回調。

我做錯了什麼?

回答

1

這就是Type Erasure

的問題是什麼意思?泛型類僅在編譯時存在。在運行時,你可以考慮泛型類的每個實例,就好像它是一個Object類的實例。

你在運行時類將是這樣的:

protected Object callback; 

@Override 
@SuppressWarnings({"unchecked"}) 
public void onAttach(final Context context) { 
    super.onAttach(context); 
    try { 
     this.callback = (Object) getActivity(); 
    } catch (final ClassCastException e) { 
     throw new ClassCastException(context.toString() + " must implement " + this.callback.getClass().getSimpleName()); 
    } 
} 

所以你沒有得到任何的異常,因爲getActivity()返回一個活動是一個Object實例