【问题标题】:<T> cannot be resolved to a type?<T> 无法解析为类型?
【发布时间】:2016-06-07 22:05:23
【问题描述】:

我想使用 jackson json 库将 json 字符串转换为 List&lt;Someclass&gt;

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();
        }
    }

所以如果我将Attribute.class 传递为type,那么它必须返回一个List&lt;Attribute&gt;

但是,这给了我一个编译时错误

T cannot be resolved to a type

我猜泛型部分在这里对我来说不是很清楚。任何帮助表示赞赏。

【问题讨论】:

  • 问题在于编译器上下文中的“T”可能是任何其他类型。使用字母 T U V 是我们用于泛型的约定,但您也可以轻松地写成 List 。为了告诉编译器它是泛型的,你必须做一些事情来区分它,否则它只是一个无法解析的类型。

标签: java json generics jackson objectmapper


【解决方案1】:

你需要在你的泛型方法中首先声明T,在你的情况下它是:

public static <T> List<T> toList(String json, Class<T> type,  ObjectMapperProperties objectMapperProperties)

有关更多信息,请查看 oracle 文档以了解通用方法:

https://docs.oracle.com/javase/tutorial/extra/generics/methods.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 2013-12-14
    • 2015-06-10
    • 2015-11-22
    相关资源
    最近更新 更多