Java 错误:Optional int 参数无法转换为 null 值
在 Java 中,当尝试使用可选的 int 参数时,您可能会遇到以下错误:
'java.lang.IllegalStateException: Optional int parameter 'id' is present but cannot be translated into a null value due to being declared as a primitive type. Consider declaring it as object wrapper for the corresponding primitive type.'
此错误的原因是 int 是一个基本数据类型,不能赋值为 null。而 Optional 对象可能包含 null 值。为了解决此问题,请将您的 int 参数声明为 Integer 类型。
例如:
// 错误:使用 int 作为参数类型
public void myMethod(Optional<int> id) {
// ...
}
// 正确:使用 Integer 作为参数类型
public void myMethod(Optional<Integer> id) {
// ...
}
通过将 int 类型更改为 Integer 类型,您可以允许 Optional 对象包含 null 值,从而避免错误。
原文地址: http://www.cveoy.top/t/topic/blbi 著作权归作者所有。请勿转载和采集!