简体   繁体   中英

Java.util.function.Function with parameter

I have a class that accept a Function<ByteBuffer, T> deserialize as constructor argument. I want the function to convert JSON to list of objects. Here's what I am trying to do

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

Obviously the syntax is wrong here. How can I fix this?

Instead of creating such a function I would rather go with utility method because ObjectMapper.readValue() throws IOException which is checked. Therefore it should be handled because we can't propagate checked exceptions outside the Function .

If you wonder how it might look like, here it is:

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;
        }
    };
}

Instead, let's consider a utility-class:

public static final ObjectMapper objectMapper = // initializing the mapper

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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