我有一个类,它在请求时初始化一些 GUI 组件:
public class ComponentInitializer<T extends View>
public abstract void initialize(T object);
现在这里是初始化所有组件的片段:
private <T extends View> void initComponents(View view) {
// ArrayList<Component<? extends View>> this.componentInitializers
for (ComponentInitializer<? extends View> initializer : this.componentInitializers) {
View object = view.findViewById(initializer.getResourceId());
if (object instanceof CheckBox) {
((ComponentInitializer<CheckBox>) initializer).initialize((CheckBox) object);
}
else if (object instanceof RadioButton) {
((ComponentInitializer<RadioButton>) initializer).initialize((RadioButton) object);
}
else if (object instanceof EditText) {
((ComponentInitializer<EditText>) initializer).initialize((EditText) object);
}
}
}
这样可行; 我测试了它。
但是......有许多对象正在扩展android.view.View
,我懒得为每个扩展的对象制作代码块View
。
else if (object instanceof ObjectExtendingView) {
((ComponentInitializer<ObjectExtendingView>) initializer).initialize((ObjectExtendingView) object);
}
是否有可能将代码片段减少为一元语句,就像这样:
for (ComponentInitializer<? extends View> initializer : this.componentInitializers) {
initializer.initialize(object); // Maybe with some casts
}
如果是,如何?如果没有,有什么解决方法?