Avoid setting field with reflection on a JDK class - fails on newer JDK versions

This commit is contained in:
ljacqu 2023-06-20 17:03:06 +02:00
parent 2e3448ab58
commit db04fd2a5b

View File

@ -40,10 +40,10 @@ public class ExceptionUtilsTest {
@Test @Test
public void shouldHandleCircularCausesGracefully() { public void shouldHandleCircularCausesGracefully() {
// given // given
IllegalStateException ise = new IllegalStateException(); ExceptionWithSettableCause exceptionWithSettableCause = new ExceptionWithSettableCause();
UnsupportedOperationException uoe = new UnsupportedOperationException(ise); UnsupportedOperationException uoe = new UnsupportedOperationException(exceptionWithSettableCause);
ReflectiveOperationException roe = new ReflectiveOperationException(uoe); ReflectiveOperationException roe = new ReflectiveOperationException(uoe);
ReflectionTestUtils.setField(Throwable.class, ise, "cause", roe); exceptionWithSettableCause.cause = roe;
// when // when
NullPointerException resultNpe = ExceptionUtils.findThrowableInCause(NullPointerException.class, uoe); NullPointerException resultNpe = ExceptionUtils.findThrowableInCause(NullPointerException.class, uoe);
@ -65,4 +65,14 @@ public class ExceptionUtilsTest {
// then // then
assertThat(result, equalTo("[MalformedURLException]: Unrecognized URL format")); assertThat(result, equalTo("[MalformedURLException]: Unrecognized URL format"));
} }
private static final class ExceptionWithSettableCause extends Exception {
Exception cause;
@Override
public synchronized Throwable getCause() {
return cause;
}
}
} }