Casting { public static <T> Optional<T> cast(Class<T> targetClass, Object instance) { return targetClass.isInstance(instance)? Optional.of(targetClass.cast(instance)): Optional.empty(); }  static Optional<T> cast(Class<T> targetClass, Object instance);  }
@Test public void valid_cast_gives_present_optional() { Object objectToCast = 12; Optional<Integer> value = cast(Integer.class, objectToCast); assertTrue("Value is not present", value.isPresent()); assertThat(value.get(), is(objectToCast)); }
@Test public void invalid_cast_gives_empty_optional() { Object objectToCast = "string"; Optional<Integer> value = cast(Integer.class, objectToCast); assertTrue("Value is present", !value.isPresent()); }
@Test(expected = IllegalArgumentException.class) public void cast_sample_usage() { Object objectToCast = "illegal"; int result = cast(Integer.class, objectToCast). filter(i -> !i.equals(0)). orElseThrow(() -> new IllegalArgumentException("Expected non-zero integer, got " + quote(objectToCast))); }