0

我有一个类,它在请求时初始化一些 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
}

如果是,如何?如果没有,有什么解决方法?

4

2 回答 2

1

像这样的东西怎么样:

private void initComponents(View view) {
    for (ComponentInitializer<? extends View> initializer : this.componentInitializers) {
        helper(initializer, view);
    }
}

private static <T extends View> void helper(ComponentInitializer<T> initializer, View view) {
        T object = (T)view.findViewById(initializer.getResourceId());
        initializer.initialize(object);
}
于 2013-04-30T01:56:28.857 回答
0

知道Textends View,您可以安全地将对象强制转换为T。然后会调用相应的方法。这应该有效:

private <T extends View> void initComponents(T view) {
    for (ComponentInitializer<? extends View> initializer : this.componentInitializers) {
        T object = (T) view.findViewById(initializer.getResourceId());
        if (object != null) {
            ((ComponentInitializer<T>) initializer).initialize((T) object);
        }
    }
}
于 2013-04-29T19:27:19.357 回答