我一直在尋找其他問題,但我仍然不明白這里發生了什么。我有這堂課:
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 的實體(從不為空)
為什么是這樣?這是什么意思,因為 Converter 被注釋了@Nullable?我該如何解決這個警告?
uj5u.com熱心網友回復:
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/lang/NonNullApi.html:
一個常見的 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注釋,因此沒有指定警告。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/477144.html
