简体   繁体   中英

Is there an equivalent of Javascript's optional chaining in Java?

 String answer = question1?.question2?.answer

Is there a way (preferably in-built) to get the property of an object where both the following scenarios are covered:

  1. If the object is null, return a null value for the attribute.
  2. Returns null for an attribute if it doesn't exist in the object.

To top this, is there a way to chain such get operations for deeply nested attributes?

Java doesn't however Groovy does. When writing Groovy you can mix java right in with it. In Groovy you can do println company?.address?.street?.name

it's possible to obtain "similar" behavior(chain) but just with custom code ( not being something inbuild)

public class TestChain 
{
    public static void main(String args[]) 
    {
        TestChain tc = new TestChain();
        Person p = tc. new Person();
        p.setName("pName").getMsg().setAge(10).getMsg();
    }
    
    class Person
    {
        String name;
        int age;
        public Person setName(String name)
        {
            this.name = name;
            return this;
        }
        
        public Person setAge(int age)
        {
            this.age = age;
            return this;
        }
        
        public Person getMsg()
        {
            System.out.println(this);
            return this;
        }
        public String toString()
        {
            return "name="+name+",age="+age;
        }
        
    }
}

Output:

name=pName,age=0
name=pName,age=10

Basically methods to be chained need to return current instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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