我有这样的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中放置一个断点时,它永远不会失败,我的活动甚至没有实现回调。
我做错了吗?
答案 0 :(得分:1)
这是什么意思?
泛型类仅在编译时存在。在运行时,您可以将泛型类的每个实例都视为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
实例的活动