繁体   English   中英

Java.util.function.Function带参数

[英]Java.util.function.Function with parameter

我有一个 class 接受Function<ByteBuffer, T> deserialize化作为构造函数参数。 我希望 function 将 JSON 转换为对象列表。 这就是我想要做的

public Function<ByteBuffer, List<MyObject>> deserialize(
    final ObjectMapper objectMapper
) {
    return objectMapper.readValue(??, new TypeReference<List<MyObject>>(){});
}

显然这里的语法是错误的。 我怎样才能解决这个问题?

而不是创建这样的function我宁愿 go 使用实用程序方法,因为ObjectMapper.readValue()抛出IOException已检查。 因此应该处理它,因为我们不能在Function之外传播已检查的异常。

如果您想知道它的外观,这里是:

public Function<ByteBuffer, List<MyObject>> deserialize(ObjectMapper objectMapper) {

    return buffer -> {
        try {
            return objectMapper.readValue(buffer.array(),new TypeReference<List<MyObject>>() {
            });
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    };
}

相反,让我们考虑一个实用程序类:

public static final ObjectMapper objectMapper = // initializing the mapper

public static List<MyObject> deserialize(ByteBuffer buffer) throws IOException {
    
    return objectMapper.readValue(buffer.array(),new TypeReference<>() {});
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM