Java abstract class function generic Type

2019-07-13 23:44发布

I created abstract class for my ArrayList holders

public abstract class ArrayHolder {
    Gson g = new Gson();
}

used like

public class MyHolder extends ArrayHolder {
    ArrayList<MyType> myList = new ArrayList<MyType>();
}

I would like to create abstract function to fill this ArrayList from String and Type argument

like this (String data is JSON in String) : This function should be rewritten

public ArrayList<T> arrayType(String data, T type){
    return g.fromJson(data, new TypeToken<ArrayList<type>(){}.getType());
}

to use it in subclass

public void fillData(String data){
    myList = arrayType(data, MyType.class);
}

How can I do this properly?

Thanks

3条回答
Rolldiameter
2楼-- · 2019-07-13 23:53

Try this...

public abstract class ArrayHolder {
    Gson g = new Gson();

    public <T> ArrayList<T> arrayType(String data){
        return g.fromJson(data, TypeToken.get(new ArrayList<T>().getClass()));
    }
}

use

public class MyCollection extends ArrayHolder {
    private ArrayList<MyType> collection;

    public void setData(String data){
        collection = arrayType(data);
    }
}
查看更多
叛逆
3楼-- · 2019-07-14 00:03

Do it like this:

public <T> ArrayList<T> arrayType(String data){
     return g.fromJson(data, new TypeToken<ArrayList<T>>(){}.getType());
}

I haven't dealt with generic typed methods, but from what I've seen, this is right.

查看更多
混吃等死
4楼-- · 2019-07-14 00:12
public <T> ArrayList<T> arrayType(String data){
    return g.fromJson(data, new TypeToken<ArrayList<T>>(){}.getType());
}
查看更多
登录 后发表回答