简体   繁体   中英

How to pass in class type to method for Gson

All,

I would like to pass in a class type as a variable, and use it to parametrize a list. For instance, I have my method as follows:

public void index(String url, Class clazz) {
    Gson gson = new Gson();
    Type listType = new TypeToken<List<clazz>>(){}.getType();
    gson.fromJson(response.body().toString(), listType);
}

Is this even possible? Note that in this case, I can't use generics.

Class is a raw type. Use it with a type parameter defined in a generic method and use that type parameter:

public <T> void index(String url, Class<T> clazz) {
    Gson gson = new Gson();
    Type listType = new TypeToken<List<T>>(){}.getType();
    gson.fromJson(response.body().toString(), listType);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM