Gracefully avoiding NullPointerException in Java

前端 未结 9 1377
夕颜
夕颜 2020-11-30 04:02

Consider this line:

if (object.getAttribute(\"someAttr\").equals(\"true\")) { // ....

Obviously this line is a potential bug, the attribute

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 04:34

    Here is my approach, needs a PropertyUtil class though, but its only written once:

    /**
     * Generic method to encapsulate type casting and preventing nullPointers.
     * 
     * @param           The Type expected from the result value.
     * @param o            The object to cast.
     * @param typedDefault The default value, should be of Type T.
     * 
     * @return Type casted o, of default.
     */
    public static  T getOrDefault (Object o, T typedDefault) {
        if (null == o) {
            return typedDefault;
        }
        return (T) o;
    }
    

    Client code can do this:

    PropertyUtil.getOrDefault(obj.getAttribute("someAttr"), "").equals("true");
    

    or, for a list:

    PropertyUtil.getOrDefault(
        genericObjectMap.get(MY_LIST_KEY), Collections.EMPTY_LIST
    ).contains(element);
    

    Or to a consumer of List, that would reject Object:

    consumeOnlyList(
        PropertyUtil.getOrDefault(
            enericObjectMap.get(MY_LIST_KEY), Collections.EMPTY_LIST
        )
    )
    

    The default might be an impl of the null object pattern https://en.wikipedia.org/wiki/Null_Object_pattern

提交回复
热议问题