简体   繁体   English

Java 可选检查 object 及其属性

[英]Java Optional check for object and its property

I wanted to check if object is not null and its property is not null then call another function.我想检查 object 是否不是 null 并且它的属性不是 null 然后调用另一个 ZC1C425268E68385D14ZA944。 I am trying to do this with Optional.我正在尝试使用 Optional 来做到这一点。

Employee is a class with a string property name. Employee 是一个带有字符串属性名称的 class。 So I wanted to check if employee object is not null and name property in it is not null then call a method.所以我想检查员工 object 是否不是 null 并且其中的名称属性不是 null 然后调用一个方法。

I tried some thing like below, but is this right approach, please correct me.我尝试了以下类似的方法,但这是正确的方法,请纠正我。

   //Employee emp; // comes from another function
    Optional.ofNullable(emp).ifPresent(obj -> Optional.ofNullable(obj.getName()).ifPresent(name ->System.out.println(name)));

This is probably what you want这可能是你想要的

Optional.ofNullable(emp).map(Employee::getName).ifPresent(System.out::println);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM