< prev index next >

src/java.base/share/classes/java/util/Optional.java

Print this page
rev 14279 : [mq]: 8140281-deprecation-optional.get

*** 124,141 **** --- 124,173 ---- public static <T> Optional<T> ofNullable(T value) { return value == null ? empty() : of(value); } /** + * Equivalent to {@link #getWhenPresent()}. * If a value is present, returns the value, otherwise throws * {@code NoSuchElementException}. * + * @deprecated + * This method's simple name {@code get} makes it the obvious method to + * call to retrieve the value from this {@code Optional}. However, it has + * no mechanism to avoid an exception if this {@code Optional} is empty. + * This tends to lead to code that mishandles empty {@code Optional} + * values. Consider using other methods that handle the case where + * the {@code Optional} might be empty, such as + * {@link #filter(java.util.function.Predicate) filter()}, + * {@link #map(java.util.function.Function) map()}, + * {@link #ifPresent(java.util.function.Consumer) ifPresent()} + * and related methods, and + * {@link #orElse(java.lang.Object) orElse()} and related methods. + * Use {@link getWhenPresent()} when it is known that a value is + * always present. + * * @return the non-{@code null} value described by this {@code Optional} * @throws NoSuchElementException if no value is present * @see Optional#isPresent() */ + @Deprecated(since="9") public T get() { + return getWhenPresent(); + } + + /** + * If a value is present, returns the value, otherwise throws + * {@code NoSuchElementException}. + * + * @apiNote + * Use this method only when it is known that a value is always present. + * + * @return the non-{@code null} value described by this {@code Optional} + * @throws NoSuchElementException if no value is present + * @see Optional#isPresent() + */ + public T getWhenPresent() { if (value == null) { throw new NoSuchElementException("No value present"); } return value; }
< prev index next >