From 4b63f240b94ebf2737d3e943c5275c4191d9fe97 Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Sun, 21 Aug 2022 11:04:56 -0400 Subject: [PATCH] Use Stream. --- .../lang3/exception/ExceptionUtils.java | 36 +++++++------------ 1 file changed, 13 insertions(+), 23 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java b/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java index 2c3fa8531..46c0e2d7f 100644 --- a/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java +++ b/src/main/java/org/apache/commons/lang3/exception/ExceptionUtils.java @@ -133,26 +133,14 @@ public static Throwable getCause(final Throwable throwable, String[] methodNames if (throwable == null) { return null; } - if (methodNames == null) { final Throwable cause = throwable.getCause(); if (cause != null) { return cause; } - methodNames = CAUSE_METHOD_NAMES; } - - for (final String methodName : methodNames) { - if (methodName != null) { - final Throwable legacyCause = getCauseUsingMethodName(throwable, methodName); - if (legacyCause != null) { - return legacyCause; - } - } - } - - return null; + return Stream.of(methodNames).map(m -> getCauseUsingMethodName(throwable, m)).filter(Objects::nonNull).findFirst().orElse(null); } /** @@ -164,19 +152,21 @@ public static Throwable getCause(final Throwable throwable, String[] methodNames */ // TODO: Remove in Lang 4.0 private static Throwable getCauseUsingMethodName(final Throwable throwable, final String methodName) { - Method method = null; - try { - method = throwable.getClass().getMethod(methodName); - } catch (final NoSuchMethodException | SecurityException ignored) { // NOPMD - // exception ignored - } - - if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) { + if (methodName != null) { + Method method = null; try { - return (Throwable) method.invoke(throwable); - } catch (final IllegalAccessException | IllegalArgumentException | InvocationTargetException ignored) { // NOPMD + method = throwable.getClass().getMethod(methodName); + } catch (final NoSuchMethodException | SecurityException ignored) { // NOPMD // exception ignored } + + if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) { + try { + return (Throwable) method.invoke(throwable); + } catch (final IllegalAccessException | IllegalArgumentException | InvocationTargetException ignored) { // NOPMD + // exception ignored + } + } } return null; }