在泛型列表的 java 中传递 Class<T> ?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2797914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing the Class<T> in java of a generic list?
提问by Rob Stevenson-Leggett
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.
我有一种从服务读取 JSON 的方法,我使用 Gson 进行序列化,并使用类型参数编写了以下方法。
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.
我正在使用 json,它只返回一个类型的数组,例如
[
{ "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:
我有一个映射到这个对象的 java 类,我们称之为 MyClass。但是要使用我的方法,我需要这样做:
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.
但是,我无法弄清楚这样做的语法。仅传递 ArrayList.class 不起作用。
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?
那么有没有办法摆脱 Class 参数,或者如何获取 MyClass 的 ArrayList 的类?
采纳答案by Eyal Schneider
You can use Bozho's solution, or avoid the creation of a temporary array list by using:
您可以使用 Bozho 的解决方案,或使用以下方法避免创建临时数组列表:
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").
此解决方案的唯一问题是您必须使用 @SuppressWarnings("unchecked") 抑制未经检查的警告。
回答by Bozho
You can't. You'd have to use unsafe cast:
你不能。你必须使用不安全的演员:
Class<List<MyClass>> clazz =
(Class<List<MyClass>>) new ArrayList<MyClass>().getClass();
回答by Rob Stevenson-Leggett
As a follow up to this, I found this in the Gson docs.
作为对此的跟进,我在 Gson 文档中找到了这个。
Type listType = new TypeToken<List<String>>() {}.getType();
Which solves the problem of getting the type safely but the TypeToken class is specific to Gson.
这解决了安全获取类型的问题,但 TypeToken 类是特定于 Gson 的。
回答by Luno Batista
If you are using SpringFramework
you could use ParameterizedTypeReference
as follows:
如果您正在使用,SpringFramework
您可以使用ParameterizedTypeReference
如下:
restClient.getDeserializedJSON(ParameterizedTypeReference<List<MyClass>>(){},url);