java <T> 无法解析为类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35622101/
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
<T> cannot be resolved to a type?
提问by Siddharth Trikha
I want to convert a json string to a List<Someclass>
using Hymanson json library.
我想将 json 字符串转换为List<Someclass>
使用 Hymanson json 库的字符串。
public static List<T> toList(String json, Class<T> type, ObjectMapperProperties objectMapperProperties){
ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper(objectMapperProperties);
try {
return objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(List.class, type));
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
So if I pass Attribute.class
as type
, then it must return a List<Attribute>
.
所以如果我通过Attribute.class
as type
,那么它必须返回一个List<Attribute>
.
However, this gives me a compile time error
但是,这给了我一个编译时错误
T cannot be resolved to a type
I guess generics part is not clear to me here. Any help is appreciated.
我想这里的泛型部分对我来说不清楚。任何帮助表示赞赏。
回答by Sach141
you need to declare T
first in your generic method, In your case it would be :
您需要T
在您的泛型方法中首先声明,在您的情况下,它将是:
public static <T> List<T> toList(String json, Class<T> type, ObjectMapperProperties objectMapperProperties)
for more info please check oracle documentation for generic methods:
有关更多信息,请查看通用方法的 oracle 文档:
https://docs.oracle.com/javase/tutorial/extra/generics/methods.html
https://docs.oracle.com/javase/tutorial/extra/generics/methods.html