Das Probem:
Ein Feld in Sub3 gehalten von Sub2, wiederum gehalten von Sub1 muss geholt werden. Vorliegend ist Sub1, wobei schon die Ref auf Sub2 NULL sein könnte. –> Folge: Mühsames Abfragen auf NULL.
Generische Lösung:
Honour to: http://winterbe.com/posts/2015/03/15/avoid-null-checks-in-java/
- Eine Methode programmieren, die enen Supplier als Parameter erhält.
/** * Used to access a field down along a hierarchical path without having to code all null checks. * @param resolver the function defining the access-path * @param <T> the result type of the optional returned * @return An optional for the desired result type. */ public static <T> Optional<T> getNullPointerExSave(Supplier<T> resolver) { try { T result = resolver.get(); return Optional.ofNullable(result); } catch (NullPointerException e) { return Optional.empty(); } }
2. Für hierarchischen (NullPointerException-sicheren) Zugriff:
Sub3 retrievedSub = getNullPointerExSave(() -> sub1.getSub2().getSub3()).orElse(null)