来自Json的Gson使用泛型超类

时间:2016-04-06 08:26:54

标签: java json generics

我正在尝试使用泛型来获取json数组,请参阅下面的工作:

public class Lookup<T extends Profile> {

    protected final Class<T> getSuperClass() {
        ParameterizedType superClass = (ParameterizedType)this.getClass().getGenericSuperclass();
        return (Class<T>)(superClass.getActualTypeArguments().length == 0 ? BasicProfile.class : superClass.getActualTypeArguments()[0]);
    }

    protected final Class<T[]> getSuperClassArray() {
        ParameterizedType superClass = (ParameterizedType)this.getClass().getGenericSuperclass();
        return (Class<T[]>)(superClass.getActualTypeArguments().length == 0 ? BasicMojangProfile[].class : superClass.getActualTypeArguments());
    }

    public void doWork() { // This Works
        String jsonText = "{id=3, name=Derp}";
        T result = new Gson().fromJson(jsonText, this.getSuperClass());
        // Will be whatever T is (defined elsewhere), unless this class
        // is created without a super class then properly defaults to
        // the BasicProfile
    }

    public void doArrayWork() { // DOES NOT WORK
        String jsonText = "[{id=3, name=Derp}]";
        T[] result = new Gson().fromJson(jsonText, ?);
        // Have tried the following (in place of the ?):
        // new TypeToken<T>(){}.getType()
        // new TypeToken<T[]>(){}.getType()
        // new TypeToken<List<T>>(){}.getType() // with List<T> result
        // this.getSuperClassArray()
    }

}

如何让doArrayWork正常运行?我不想将T作为参数传递给方法。

1 个答案:

答案 0 :(得分:2)

您可以使用Array.newInstance(this.getSuperClass(), 0).getClass()

这会根据传递给方法的类创建一个数组,然后在该数组上调用getCLass()来获取表示该数组的真实类对象。