通过类< T>在通用列表的Java? [英] Passing the Class<T> in java of a generic list?

查看:73
本文介绍了通过类< T>在通用列表的Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从服务中读取JSON的方法,我使用Gson来完成我的序列化,并使用类型参数编写了以下方法。

  public T getDeserializedJSON(Class< T> aClass,String url)
{
Reader r = getJSONDataAsReader(url);
Gson gson = new Gson();
返回gson.fromJson(r,aClass);
}

我正在使用json,它只返回一个类型的数组,例如 p>

  [
{prop:value}
{prop:value}



$ b

我有一个映射到这个对象的java类,我们称之为MyClass。然而,要使用我的方法,我需要这样做:

  RestClient< ArrayList< MyClass>> restClient = new RestClient< ArrayList< MyClass>>(); 
ArrayList< MyClass> results = restClient.getDeserializedJSON(ArrayList< MyClass> .class,url);

但是,我无法弄清楚它的语法。传递只是ArrayList.class不起作用。

那么有什么方法可以摆脱Class参数,或者如何获取MyClass的ArrayList类?

解决方案

您可以使用Bozho的解决方案,或者避免使用以下代码创建临时数组列表:

 类< List< MyClass>> clazz =(Class)List.class; 

这个解决方案唯一的问题是你必须用@SuppressWarnings(unchecked )。


I have a method for reading JSON from a service, I'm using Gson to do my serialization and have written the following method using type parameters.

public T getDeserializedJSON(Class<T> aClass,String url)
{
    Reader r = getJSONDataAsReader(url);
    Gson gson = new Gson();
    return gson.fromJson(r, aClass);
}

I'm consuming json which returns just an array of a type e.g.

[
 { "prop":"value" }
 { "prop":"value" }
]

I have a java class which maps to this object let's call it MyClass. However to use my method I need to do this:

RestClient<ArrayList<MyClass>> restClient = new RestClient<ArrayList<MyClass>>();
ArrayList<MyClass> results = restClient.getDeserializedJSON(ArrayList<MyClass>.class, url);

However, I can't figure out the syntax to do it. Passing just ArrayList.class doesn't work.

So is there a way I can get rid of the Class parameter or how do I get the class of the ArrayList of MyClass?

解决方案

You can use Bozho's solution, or avoid the creation of a temporary array list by using:

Class<List<MyClass>> clazz = (Class) List.class;

The only problem with this solution is that you have to suppress the unchecked warning with @SuppressWarnings("unchecked").

这篇关于通过类&lt; T&gt;在通用列表的Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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