简体   繁体   English

如何传递要返回的列表的类型?

[英]How can I pass the type for the List I want return?

My scenario: 我的情况:

I get a jsonArray, I want to convert this jsonArray to a List of desired type; 我得到一个jsonArray,我想将此jsonArray转换为所需类型的列表。 ie List<Integer> , List<String> etc. List<Integer>List<String>等。

Suppose I have the following method: 假设我有以下方法:

public static List jsonArrayToJavaList(JsonArray jsonArray, TYPE TYPE) {
    return new Gson().fromJson(jsonArray, new TypeToken<List<TYPE>>() {}.getType());
}

How do I pass in the TYPE ? 如何传递TYPE

I want to do this because this method could be used by other people and I don't want to duplicate this code for each type of list I want... 我想要这样做是因为其他人可以使用此方法,并且我不想为我想要的每种列表类型重复此代码...

I also tried: 我也尝试过:

public static List jsonArrayToJavaList(JsonArray jsonArray, final Class c) {
    return new Gson().fromJson(jsonArray, new TypeToken<List<c>>() {}.getType());
}

I see the error saying unknown class c. 我看到错误提示未知的c类。

Java doesn't yet provide an official way to represent generic types . Java尚未提供表示通用类型的正式方法 As stated in the javadoc , the TypeToken has been provided in order to give the possibility to represent these types. javadoc中所述,提供了TypeToken以便表示这些类型。 So, the simple solution would be to use it as a parameter to the jsonArrayToJavaList method. 因此,简单的解决方案是将其用作jsonArrayToJavaList方法的参数。 However it will be just an indirection to the call of fromJson. 但是,这只是对fromJson调用的间接调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果无法传入类类型,如何返回通用数组? - How to return a generic array if I can't pass in the class type? 如果返回类型是列表,我该如何钩住 <string> 在xposed? - how can i hook if return type is a list<string> in xposed? 我可以通过Web服务中对象的返回类型传递xml对象吗? - can i pass the xml object with return type of object in web services 如何传递数组类型的变量 - How can I pass a variable of type array Spring中返回String类型的算法怎么改成返回List类型? - How can I change an algorithm returning a String type to return a List type in Spring? 如何返回 laravel 中的内容类型? - How can i return with Content type in laravel? Java - 如何将方法的返回类型作为参数传递? - Java - How do I pass the return type of a method as parameter? 为什么我可以返回我的列表未指定类型的列表 <T> 退货类型? - Why Can I Return A List Of A Type Not Specified By My List<T> Return Type? 如何将类型 T 传递给方法并让它推断类型? - How can I pass a type T to a method and have it infer the type? 如何为参数列表和/或返回类型中的“任何映射条目”值创建通用方法签名? - How can I create a generic method signature for “any map entry” value in the parameter list and/or return type?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM