2

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

Marek Sebera
  • 39,650
  • 37
  • 158
  • 244

3 Answers3

3

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);
    }
}
Marek Sebera
  • 39,650
  • 37
  • 158
  • 244
John B
  • 32,493
  • 6
  • 77
  • 98
2
public <T> ArrayList<T> arrayType(String data){
    return g.fromJson(data, new TypeToken<ArrayList<T>>(){}.getType());
}
Stanislav Levental
  • 2,165
  • 1
  • 14
  • 28
2

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.

Matt Fenwick
  • 48,199
  • 22
  • 128
  • 192
Ryan Amos
  • 5,422
  • 4
  • 36
  • 56
  • `TypeToken` should not be created using an anonymous inner class but by using `TypeToken.get(...)` – John B Dec 08 '11 at 20:34
  • @JohnB what is bad on creating TypeToken via inner class? – Marek Sebera Dec 08 '11 at 20:41
  • You don't know what non-public abstract methods Google needs in the implementation. They made the class abstract and hid the actual implementation class as a data-hiding mechanism. That is why they provide the `get` method to retrieve a concrete instance. – John B Dec 08 '11 at 20:47