Java方法参数泛型类型

时间:2015-08-11 08:44:23

标签: java generics

我有一个班级:

public abstract class BindingFragment<T extends ViewDataBinding> extends Fragment {
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        T binding = DataBindingUtil.bind(view);
        onViewBind(binding);
        onViewBind(createViewBind(view));
        onViewBind((T)DataBindingUtil.bind(view));
        onViewBind(DataBindingUtil.bind(view)); //this line compile error
    }`

    public abstract void onViewBind(T binding);

    private T createViewBind(View view){
        return DataBindingUtil.bind(view);
    }
}

方法DataBindingUtil.bind(view)签名如下:

public static <T extends ViewDataBinding> T bind(View root)

我测试了一些在BindingFragment类中调用onViewBind(T binding)的方法,但onViewBind(DataBindingUtil.bind(view))上面的行无法通过。有人可以告诉我为什么吗?

2 个答案:

答案 0 :(得分:1)

您必须在onViewBind(DataBindingUtil.bind(view)); //this line compile error

处明确提供T.

因为在以下方法中你接受参数为T。

public abstract void onViewBind(T binding);

如果您使用以下方法,则无需提供任何明确的投射。

public abstract void onViewBind(ViewDataBinding binding);

答案 1 :(得分:0)

违规行

 onViewBind(DataBindingUtil.bind(view)); //this line compile error

在Java 1.8中编译,但在Java 1.7中编译(在Eclipse中测试时)。 现在,Java泛型类型的编译器处理是一个移动目标。

在Java 1.7中,您可以使用

 onViewBind(DataBindingUtil.<T>bind(view)); 

避免演员。