Exceptions { public static <T extends Throwable> T anyCauseOf(Throwable ex, Class<T> type) { if (type.isInstance(ex)) { return (T) ex; } Throwable cause = ex.getCause(); if (cause != null) { return anyCauseOf(cause, type); } return null; } private  Exceptions(); static Throwable rootCause(Throwable ex); static T anyCauseOf(Throwable ex, Class<T> type); static Throwable firstCauseNotOf(Throwable ex, Class<?>... types);  }
@Test public void testAnyOf() { A top=new A("a",new B("b",new D("d",new B("root")))); Throwable anyCauseOf = Exceptions.anyCauseOf(top,B.class); Assert.assertEquals("type", B.class,anyCauseOf.getClass()); Assert.assertEquals("message", "b",anyCauseOf.getMessage()); anyCauseOf = Exceptions.anyCauseOf(top,C.class); Assert.assertNull(anyCauseOf); anyCauseOf = Exceptions.anyCauseOf(top,A.class); Assert.assertEquals("type", A.class,anyCauseOf.getClass()); Assert.assertEquals("message", "a",anyCauseOf.getMessage()); }