如何使用类名动态设置ArrayList类型? [英] How to set an ArrayList Type dynamically using the class name?

查看:64
本文介绍了如何使用类名动态设置ArrayList类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Gson库,通过以下代码将JSON字符串转换为ArrayList对象:

Using the Gson library, I convert a JSON string to an ArrayList Object by following code:

posts = gson.fromJson(json, new TypeToken<List<Post>>(){}.getType());

并且我使用以下代码将json转换为objec类:

and I use the following code for convert a json to a class objec:

obj = gson.fromJson(json, Class.forName(fullClassName));

您会在第二个代码中看到我使用反射来指定类的类型;但是对于第一个代码,我不知道如何使用反射来指定列表的类型.

You see in the second code that I used reflection to specify the type of class; but for the first code, I don't know how to specify the type of list using reflection.

我该怎么办?!

推荐答案

因此,据我了解,您需要对对象列表进行反序列化,但是在编译时类型未知,但是您是在动态提供它?您可能想为您的类型使用类似的内容:

So, from what I understand you need to deserialize list of objects but type isn't known on compile time but you are providing it dynamically?
You probably want to use something like that for your type:

TypeToken.getParameterized(List.class, Class.forName("foo.bar.MyDynamicType"))

这将创建与

new TypeToken<List<MyDynamicType>>(){}.getType()

这篇关于如何使用类名动态设置ArrayList类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆