簡體   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