Cast { public static <T> T castOrFail(Object object, Class<T> clazz) { requireNonNull(clazz); if (object == null) { throw new NoSuchElementException("null is not an instance of " + clazz.getName()); } return Optional.of(object) .filter(o -> clazz.isAssignableFrom(o.getClass())) .map(clazz::cast) .orElseThrow(NoSuchElementException::new); } private  Cast(); static Optional<T> cast(Object object, Class<T> clazz); static T castOrFail(Object object, Class<T> clazz);  }
@Test void castOrFail() { assertThrows(NullPointerException.class, () -> Cast.castOrFail("value", null)); assertThrows(NoSuchElementException.class, () -> Cast.castOrFail(null, String.class)); assertThrows(NoSuchElementException.class, () -> Cast.castOrFail(1, String.class)); assertEquals(1, Cast.castOrFail(1L, Number.class).intValue()); }