Java 8 新特性尝试 系列之一Optional类

这篇博客探讨了Java 8中引入的Optional类,它帮助开发者更优雅地处理可能为空的对象,避免空指针异常。通过介绍Optional类的不可变性、实例化方式及其泛型使用,文章旨在提高代码的健壮性和可读性。
摘要由CSDN通过智能技术生成

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值