这个问题涉及Android示例,但这更像是纯Java问题。
考虑以下课程:
interface MyCallback {
/* ... */
}
class MyActivity extends Activity implements MyCallback {
/* ... */
// Note to non-Android guys: Activity is a subclass of Context.
}
class MyAdapter {
<C extends Context & MyCallback> MyAdapter(C context) {
/*
* For some reason I want to delegate all instanceof-checks and
* casts to a caller. So at this point I want to be sure
* context is already of a proper type, hence generic parameter.
*/
}
}
您能解释一下我如何通常声明一个我可以传递给这样的构造函数的变量吗?
有一次,我只有一个对活动对象的引用。我可以执行必要的检查(是否实现MyCallback)但我不能将其作为参数传递,除非我明确指定了适当的类型。
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
MyAdapter adapter;
// 1. won't compile:
adapter = new MyAdapter(getActivity());
// 2. won't compile:
adapter = new MyAdapter((MyCallback) getActivity());
// 3. invalid notation:
adapter = new MyAdapter((Context & MyCallback) getActivity());
// 4. works but severely limits flexibility:
adapter = new MyAdapter((MyActivity) getActivity());
}
另一种选择是这样做:
adapter = createAdater(getActivity())
private <C extends Context & ListToMapCallback>
MyAdapter createAdapter(Activity activity) {
// check if activity is castable
return new MyAdapter((C) activity);
}
虽然有点难看但没关系。我知道这不是什么大问题,但我很好奇是否可以在不创建新方法的情况下获得相同的结果(由于“相同的擦除”错误,我无法生成重写方法)。
谢谢!