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

前端 未结 14 745
心在旅途
心在旅途 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条回答
  • 2021-01-27 16:04

    See: https://blogs.oracle.com/darcy/project-coin:-the-final-five-or-so (specifically "Elvis and other null safe operators").

    The result is that this feature was considered for Java 7, but was not included.

    0 讨论(0)
  • 2021-01-27 16:06

    Java does not have the exact syntax but as of JDK-8, we have the Optional API with various methods at our disposal. So, the C# version with the use of null conditional operator:

    return person?.getName()?.getGivenName(); 
    

    can be written as follows in Java with the Optional API:

     return Optional.ofNullable(person)
                    .map(e -> e.getName())
                    .map(e -> e.getGivenName())
                    .orElse(null);
    

    if any of person, getName or getGivenName is null then null is returned.

    0 讨论(0)
  • 2021-01-27 16:07

    This syntax does not exist in Java, nor is it slated to be included in any of the upcoming versions that I know of.

    0 讨论(0)
  • 2021-01-27 16:07

    If someone is looking for an alternative for old java versions, you can try this one I wrote:

    /**
     * Strong typed Lambda to return NULL or DEFAULT VALUES instead of runtime errors. 
     * if you override the defaultValue method, if the execution result was null it will be used in place
     * 
     * 
     * Sample:
     * 
     * It won't throw a NullPointerException but null.
     * <pre>
     * {@code
     *  new RuntimeExceptionHandlerLambda<String> () {
     *      @Override
     *      public String evaluate() {
     *          String x = null;
     *          return x.trim();
     *      }  
     *  }.get();
     * }
     * <pre>
     * 
     * 
     * @author Robson_Farias
     *
     */
    
    public abstract class RuntimeExceptionHandlerLambda<T> {
    
        private T result;
    
        private RuntimeException exception;
    
        public abstract T evaluate();
    
        public RuntimeException getException() {
            return exception;
        }
    
        public boolean hasException() {
            return exception != null;
        }
    
        public T defaultValue() {
            return result;
        }
    
        public T get() {
            try {
                result = evaluate();
            } catch (RuntimeException runtimeException) {
                exception = runtimeException;
            }
            return result == null ? defaultValue() : result;
        }
    
    }
    
    0 讨论(0)
  • 2021-01-27 16:12

    That's actually Groovy's safe-dereference operator. You can't use it in pure Java (sadly), so that post is simply wrong (or more likely slightly misleading, if it's claiming Groovy to be the "latest version of Java").

    0 讨论(0)
  • 2021-01-27 16:16

    If this is not a performance issue for you, you can write

    public String getFirstName(Person person) {
      try {
         return person.getName().getGivenName();
      } catch (NullPointerException ignored) {
         return null;
      }
    } 
    
    0 讨论(0)
提交回复
热议问题