将非特定类传递到另一个类

时间:2016-02-27 02:51:18

标签: java android

我发现自己在所有片段中一遍又一遍地编写这部分代码:

public class Tab1 extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            Bundle bundle = this.getArguments();
            if (bundle == null) {
                return null;
            }
            @SuppressWarnings("unchecked")
            List<Map<String, String>> data = (List<Map<String, String>>) bundle.getSerializable("data");
            / ........../
    }

}

我不确定如何将它重构为一个类以避免重复。我收到一个错误,将类的引用(可能是Tab1或Tab2或Tab3)传递给它:

public class GetBundle {

    public <T> T serialize(Class clazz,String key){
        Bundle bundle = clazz.getArguments();
                        ^^^^ 
        if (bundle == null) {
            return null;
        }
        @SuppressWarnings("unchecked")
        T data = (T) bundle.getSerializable(key);
        return data;
    }
}

1 个答案:

答案 0 :(得分:1)

serialize方法中,Class类型没有方法getArguments,因此您应将clazz类型更改为Fragment

像这样:

public <T> T serialize(Fragment clazz,String key){