Java “?” Operator for checking null - What is it? (Not Ternary!)

前端 未结 14 770
心在旅途
心在旅途 2021-01-27 15:38

I was reading an article linked from a slashdot story, and came across this little tidbit:

Take the latest version of Java, which tries to make null-poi

14条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-27 16:24

    Since Android does not support Lambda Functions unless your installed OS is >= 24, we need to use reflection.

    // Example using doIt function with sample classes
    public void Test() {
        testEntry(new Entry(null));
        testEntry(new Entry(new Person(new Name("Bob"))));
    }
    
    static void testEntry(Entry entry) {
        doIt(doIt(doIt(entry,  "getPerson"), "getName"), "getName");
    }
    
    // Helper to safely execute function 
    public static  R doIt(T obj, String methodName) {
        try {
           if (obj != null) 
               return (R)obj.getClass().getDeclaredMethod(methodName).invoke(obj);
        } catch (Exception ignore) {
        }
        return null;
    }
    
    // Sample test classes
        static class Entry {
            Person person;
            Entry(Person person) { this.person = person; }
            Person getPerson() { return person; }
        }
    
        static class Person {
            Name name;
            Person(Name name) { this.name = name; }
            Name getName() { return name; }
        }
    
        static class Name {
            String name;
            Name(String name) { this.name = name; }
            String getName() {
                System.out.print(" Name:" + name + " ");
                return name;
            }
        }
    }
    

提交回复
热议问题