Monday, January 13, 2020

Java Generics Example

private <E> E getUpdatedObject(E oldItem, E newItem) {
    Gson gson = new Gson();
    Type type = new TypeToken<E>() {
    }.getType();
    E item = null;
    if (Objects.isNull(oldItem) && Objects.nonNull(newItem)) {
        item = newItem;
    } else if (Objects.nonNull(oldItem) && Objects.isNull(newItem)) {
        item = oldItem;
    } else {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            
            String elements = gson.toJson(newItem, type);
            item = objectMapper.readerForUpdating(oldItem).readValue(elements);
        } catch (IOException e) {
            LOGGER.error("error updating object: {}", e);
        }
    }
    return item;
}

No comments:

Post a Comment