<T>无法解析为某种类型?

Sid*_*kha 8 java generics json jackson objectmapper

我想将json字符串转换为List<Someclass>使用jackson 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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

所以,如果我通过Attribute.classtype,那么它必须返回List<Attribute>.

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

T cannot be resolved to a type
Run Code Online (Sandbox Code Playgroud)

我想泛型部分对我来说并不清楚.任何帮助表示赞赏.

Sac*_*141 15

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

public static <T> List<T> toList(String json, Class<T> type,  ObjectMapperProperties objectMapperProperties)
Run Code Online (Sandbox Code Playgroud)

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

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