首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >非注释参数重写@NonNullApi参数

非注释参数重写@NonNullApi参数
EN

Stack Overflow用户
提问于 2022-05-18 08:33:01
回答 1查看 2K关注 0票数 0

我一直在寻找其他的问题,但我仍然不明白这是怎么回事。我有一节课:

代码语言:javascript
复制
package com.test.service.database.converter;

import com.test.service.database.dao.DocumentType;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class DocumentStringConverter implements Converter<DocumentType, String> {

    @Override
    public String convert(DocumentType documentType) {
        return Optional.ofNullable(documentType).map(DocumentType::type).orElse(null);
    }
}

它实现了这个Spring接口:

代码语言:javascript
复制
package org.springframework.core.convert.converter;

import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

@FunctionalInterface
public interface Converter<S, T> {

    @Nullable
    T convert(S source);

    default <U> Converter<S, U> andThen(Converter<? super T, ? extends U> after) {
        Assert.notNull(after, "After Converter must not be null");
        return (S s) -> {
            T initialResult = convert(s);
            return (initialResult != null ? after.convert(initialResult) : null);
        };
    }
}

IntelliJ给出了在

代码语言:javascript
复制
public String convert(DocumentType documentType) {

这说明

Not注释参数重写@NonNullApi参数documentType --要转换的源对象,它必须是S的一个实例(从不为null)

为什么会这样呢?因为转换器是用@Nullable注释的,这意味着什么?我该怎么解决这个警告呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-18 09:38:37

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/lang/NonNullApi.html

一种常见的Spring注释,用于声明参数和返回值在给定包的默认情况下是不可空的。

这是org/springframework/core/convert/converter/package-info.java

代码语言:javascript
复制
/**
 * SPI to implement Converters for the type conversion system.
 */
@NonNullApi       // !!!!!!!!!!!!
@NonNullFields
package org.springframework.core.convert.converter;

可以使用@NonNullApi注释在方法级别重写@Nullable,以防止对可能返回null的方法发出警告,这就是您在org.springframework.core.convert.converter.Converter中看到的

代码语言:javascript
复制
@FunctionalInterface
public interface Converter<S, T> {

    /**
     * Convert the source object of type {@code S} to target type {@code T}.
     * @param source the source object to convert, which must be an instance of {@code S} (never {@code null})
     * @return the converted object, which must be an instance of {@code T} (potentially {@code null})
     * @throws IllegalArgumentException if the source cannot be converted to the desired target type
     */
    @Nullable            // !!!!!!!!!!
    T convert(S source);

在重写方法时,您没有指定@Nullable注释,因此没有指定警告。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72285740

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档