在 Java 中使用 Optional 类时无法将对象转换为字符串 [英] Object cannot be converted to string when using Optional class in Java
问题描述
我有以下代码试图使用 Optional 类:
I have the following code trying to use the Optional class:
import java.util.Optional;
// one class needs to have a main() method
public class HelloWorld
{
public String orelesMethod() {
return "hello";
}
public void test() {
String value;
value = Optional.ofNullable(null).orElse(orelesMethod());
System.out.println(value);
}
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
HelloWorld hello = new HelloWorld();
hello.test();
}
}
编译时,它说:
incompatible types: Object cannot be converted to String
value = Optional.ofNullable(null).orElse(orelesMethod());
我不知道是什么问题,有人可以帮忙吗?
I can not find it out what is the problem, can anyone help on it?
谢谢!
推荐答案
您已将 value
定义为 String
类型,但 Optional.ofNullable(null)
返回 Optional
因为任何对象类型都可以是 null
并且您没有指定实际类型.然后你在 Optional
类型的对象上调用 orElse
并且因为 T
是 Object
,orElse
方法返回一个类型为 Object
的对象,该对象不能转换为 String
.
You have defined value
to be of type String
, but Optional.ofNullable(null)
returns Optional<Object>
because any object type can be null
and you did not specify the actual type. Then you are calling orElse
on the object of type Optional<Object>
and because T
is Object
, the orElse
method returns an object of type Object
which cannot be converted to String
.
因此需要在调用ofNullable
时指定类型:
Therefore you need to specify the type while calling ofNullable
:
value = Optional.<String>ofNullable(null).orElse(orelesMethod());
您可能还想使用 orElseGet
方法,以便在可选项包含值时不调用 orelesMethod
.
You might also want to use orElseGet
method in order not to call orelesMethod
when the optional contains value.
这篇关于在 Java 中使用 Optional 类时无法将对象转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!