use*_*911 7 java nullable intellij-idea spring-boot
我一直在寻找其他问题,但仍然不明白这里发生了什么。\n我有这样的课程:
\npackage 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}\nRun Code Online (Sandbox Code Playgroud)\n它实现了这个 Spring 接口:
\npackage 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}\nRun Code Online (Sandbox Code Playgroud)\nIntelliJ 给出了关于参数的警告
\npublic String convert(DocumentType documentType) {\nRun Code Online (Sandbox Code Playgroud)\n表明
\n\n\n未注释的参数会覆盖@NonNullApi参数
\n
\n\ndocumentType \xe2\x80\x93 要转换的源对象,它必须是 S 的实例(绝不为 null)
\n
为什么是这样?既然 Converter 带有注释,这意味着什么@Nullable?以及如何解决这个警告?
来自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,因此也没有指定警告。
| 归档时间: |
|
| 查看次数: |
9542 次 |
| 最近记录: |