ObjectUtil { public static <S, T> Optional<T> safeCast(final S candidate, final Class<T> targetClass) { return targetClass.isInstance(candidate) ? Optional.of(targetClass.cast(candidate)) : Optional.empty(); } private  ObjectUtil(); static Optional<T> safeCast(final S candidate,
                                              final Class<T> targetClass);  }
@Test public void testSafeCastSimple() { Number testValue = new Integer(10); Integer targetValue = safeCast(testValue, Integer.class) .orElse(null); assertSame(testValue, targetValue); }
@Test public void testFailedCastNoError() { Object testValue = new Object(); Integer targetValue = safeCast(testValue, Integer.class) .orElse(null); assertNull(targetValue); }