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

前端 未结 14 751
心在旅途
心在旅途 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: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.
     * 
     * {@code
     *  new RuntimeExceptionHandlerLambda () {
     *      @Override
     *      public String evaluate() {
     *          String x = null;
     *          return x.trim();
     *      }  
     *  }.get();
     * }
     * 
     * 
     * 
     * @author Robson_Farias
     *
     */
    
    public abstract class RuntimeExceptionHandlerLambda {
    
        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;
        }
    
    }
    

提交回复
热议问题