java泛型方法产生错误的类型

xmakbtuz  于 2021-06-29  发布在  Java
关注(0)|答案(0)|浏览(1035)

例如,有一个泛型类型为的方法:

public static <T extends Serializable> ArrayDeque<Pair<String, T>> deserialize(String input) 
  throws IOException {

  // Pair is java.io.Serializable: Pair<F extends Serializable, S extends Serializable>
  ArrayDeque<Pair<String, T>> transformedResult = new ArrayDeque<>();

  // The issue is here with the constructing TypeReference
  List<Map<String, T>> result = objectMapper.readValue(input,
            new TypeReference<List<Map<String, T>>>() {
            });

  // Here goes the transformation of the list in the final result; it does not matter in this context
  return transformedResult;
}

我按原样调用此方法:

// CustomObject implements Serializable
Deque<Pair<String, CustomObject>> result = deserialize("input");

我想这需要 T 作为 CustomObject 创造 TypeReference 作为 TypeReference<List<Map<String, CustomObject>>> 事实上,当我运行单元测试时,它得到一个错误 Serializable :

com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
Cannot construct instance of `java.io.Serializable` (no Creators, like default construct, exist):
abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
at [Source: (String)"string-to-parse-goes-here"; line: 1, column: 13] (through reference chain: java.util.ArrayList[0]->java.util.LinkedHashMap["part-of-the-string-to-parse"])

所以我假设路线是 because of the "type erasure" the T is promoted into the highest constrained type 在与 new TypeReference<List<Map<String, T>>> .
问题:有没有可能将当前的方法转换为保持泛型方法来构造不同类型的typereference?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题