[英]Generics in jackson for array deserialisation
I'd like to refactor the following methods using Generics or something different I'm not able to come up with. 我想使用泛型或我无法提供的其他方法来重构以下方法。
public Double[] reverseDoubles() throws IOException {
String sarray = get.array();
Double[] array = mapper.readValue(sarray, Double[].class);
return ArrayUtils.reverse(array);
}
public Long[] reverseLongs() throws IOException {
String sarray = get.array();
Long[] array = mapper.readValue(sarray, Long[].class);
return ArrayUtils.reverse(array);
}
I'm expecting to refactor those all methods into only one with the following signature: 我希望将所有这些方法重构为一个具有以下签名的方法:
public <T> T[] reverse() throws IOException {
...
}
You can't perform this without accepting element's type in reverse
. 如果不接受reverse
元素的类型,则无法执行此操作。 However if passing the type is acceptable for you, then you can use Array.newInstance
to create the required array class during run-time: 但是,如果您可以接受传递类型,则可以在运行时使用Array.newInstance
创建所需的数组类:
public <T> T[] reverse(Class<T> elementType) throws IOException {
String sarray = get.array();
Class<?> arrayType = Array.newInstance(elementType, 0).getClass();
T[] array = (T[]) mapper.readValue(sarray, arrayType);
return ArrayUtils.reverse(array);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.