我想使用泛型或我无法想出的不同方法来重构以下方法。
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);
}
我希望将所有方法重构为具有以下签名的方法:
public <T> T[] reverse() throws IOException {
...
}
最佳答案
如果不接受 reverse
中元素的类型,则无法执行此操作。但是,如果您可以接受传递类型,那么您可以使用 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);
}
关于java - Jackson 中用于数组反序列化的泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39506498/