未注释的参数覆盖了@NonNullApi参数。

7

我一直在看其他问题,但我仍然不明白这里发生了什么。 我有这个类:

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接口的内容如下:

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在参数上发出警告

public String convert(DocumentType documentType) {

该警告表示未注释的参数覆盖了@NonNullApi参数

documentType - 要转换的源对象,必须是S的一个实例(永远不为null)

为什么会出现这种情况?这意味着什么,因为Converter带有@Nullable注释?我该如何解决此警告?

2个回答

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

@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);

在你重写的方法中,你没有指定@Nullable注解,因此会出现警告。

我理解 "// !!!!!!!!!!!!" 的存在是因为让方法可为空但类却不可为空这种情况非常反直觉。 - user3258911
不,那只是我的注释,用于标记特定的感兴趣的代码行 =) - dekkard
2
为了解决这个问题,我添加了package-info.java文件,并添加了注释NonNullFields、NonNullApi,现在它可以正常工作了。谢谢。 - Pravind Kumar

2
通过在与类文件同一包中添加一个package-info.java文件,解决了此警告。
@NonNullApi
package com.my.demo;

import org.springframework.lang.NonNullApi;


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接