未注释的参数会覆盖@NonNullApi参数

use*_*911 7 java nullable intellij-idea spring-boot

我一直在寻找其他问题,但仍然不明白这里发生了什么。\n我有这样的课程:

\n
package com.test.service.database.converter;\n\nimport com.test.service.database.dao.DocumentType;\nimport org.springframework.core.convert.converter.Converter;\nimport org.springframework.stereotype.Component;\n\nimport java.util.Optional;\n\n@Component\npublic class DocumentStringConverter implements Converter<DocumentType, String> {\n\n    @Override\n    public String convert(DocumentType documentType) {\n        return Optional.ofNullable(documentType).map(DocumentType::type).orElse(null);\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

它实现了这个 Spring 接口:

\n
package org.springframework.core.convert.converter;\n\nimport org.springframework.lang.Nullable;\nimport org.springframework.util.Assert;\n\n@FunctionalInterface\npublic interface Converter<S, T> {\n\n    @Nullable\n    T convert(S source);\n\n    default <U> Converter<S, U> andThen(Converter<? super T, ? extends U> after) {\n        Assert.notNull(after, "After Converter must not be null");\n        return (S s) -> {\n            T initialResult = convert(s);\n            return (initialResult != null ? after.convert(initialResult) : null);\n        };\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

IntelliJ 给出了关于参数的警告

\n
public String convert(DocumentType documentType) {\n
Run Code Online (Sandbox Code Playgroud)\n

表明

\n
\n

未注释的参数会覆盖@NonNullApi参数

\n
\n
\n

documentType \xe2\x80\x93 要转换的源对象,它必须是 S 的实例(绝不为 null)

\n
\n

为什么是这样?既然 Converter 带有注释,这意味着什么@Nullable?以及如何解决这个警告?

\n

dek*_*ard 4

来自Spring 官方文档

一个常见的 Spring 注释,用于声明给定包的参数和返回值默认为不可为空。

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

/**
 * SPI to implement Converters for the type conversion system.
 */
@NonNullApi       // !!!!!!!!!!!!
@NonNullFields
package org.springframework.core.convert.converter;
Run Code Online (Sandbox Code Playgroud)

@NonNullApi可以在方法级别使用@Nullable注释覆盖,以防止可能返回 null 的方法出现警告,这就是您在以下内容中看到的内容org.springframework.core.convert.converter.Converter

@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);
Run Code Online (Sandbox Code Playgroud)

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

  • 为了解决这个问题,我添加了 package-info.java 并添加了注释 NonNullFields NonNullApi,它对我有用。谢谢。 (3认同)