Java abstract class function generic Type

2019-07-13 23:47发布

问题:

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

回答1:

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);
    }
}


回答2:

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


回答3:

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.