Optional类,可以使用该类来判断是否为空
package optional; import javax.swing.text.html.Option; import java.util.Optional; /** * * @author smart 2019/3/25 */ public class OptionalExercise { public static void main(String[] args) { Integer integer = null; Integer integer1 = new Integer(11); Optional<Integer> optionalInteger = Optional.ofNullable(integer); System.out.println(optionalInteger.isPresent()); System.out.println(optionalInteger.orElse(new Integer(0))); System.out.println(Optional.of(integer1).orElse(new Integer(0))); System.out.println(Optional.ofNullable(integer1).get()); System.out.println(Optional.empty()); System.out.println(OptionalExercise.class.getClassLoader()); System.out.println(OptionalExercise.class.getClassLoader().getParent()); System.out.println(OptionalExercise.class.getClassLoader().getParent().getParent()); System.out.println(OptionalExercise.class.getPackage()); System.out.println(OptionalExercise.class.getClassLoader().getParent().getResource("")); System.out.println(OptionalExercise.class.getClassLoader().getResource("optional")); } }
Optional类是不可变的且不能不实例化,是一个泛型类,下面是该泛型类的定义
package java.util; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; /** * A container object which may or may not contain a non-null value. * If a value is present, {@code isPresent()} will return {@code true} and * {@code get()} will return the value. * * <p>Additional methods that depend on the presence or absence of a contained * value are provided, such as {@link #orElse(java.lang.Object) orElse()} * (return a default value if value not present) and * {@link #ifPresent(java.util.function.Consumer) ifPresent()} (execute a block * of code if the value is present). * * <p>This is a <a href="../lang/doc-files/ValueBased.html">value-based</a> * class; use of identity-sensitive operations (including reference equality * ({@code ==}), identity hash code, or synchronization) on instances of * {@code Optional} may have unpredictable results and should be avoided. * * @since 1.8 */ public final class Optional<T> { /** * Common instance for {@code empty()}. */ private static final Optional<?> EMPTY = new Optional<>(); /** * If non-null, the value; if null, indicates no value is present */ private final T value; /** * Constructs an empty instance. * * @i