• java8--- Optional使用


      https://yq.aliyun.com/articles/716209?spm=a2c4e.11153940.0.0.6a255562myIiAj

    正确使用举例
    
    0、经典使用    
            Employee employee1 = new Employee("employee1");
            Employee employee2 = new Employee("employee1");
            Company company = new Company("company");
            List<Employee> list = Arrays.asList(employee1,employee2);
            company.setEmployees(list);
            // 判断公司里面有没有员工  由返回员工列表 没有返回一个空的集合
            Optional<Company> optional = Optional.ofNullable(company);
            System.out.println(optional.map(com -> com.getEmployees()).orElse(Collections.emptyList()));
    
    1、ifPresent()判断替换if
        //待优化
        String referer = request.getHeader("referer");
        if (StringUtils.isNotEmpty(referer)) {
            request.getSession().setAttribute("referer", referer);
        }
        //java8
        Optional.ofNullable(request.getHeader("referer"))
            .ifPresent(s -> {
                request.getSession().setAttribute("referer", s);
        });
    
    2、用orElse替换 if...else...
         //待优化
        String redirect = (String) session.getAttribute("referer");
        if (redirect == null){
            result.put("referer","/index"); 
        }else {
            result.put("referer",redirect);
        }
    
        //java8
        Optional<String> redirect = Optional.ofNullable((String) session.getAttribute("referer"));
        result.put("referer",redirect.orElse("/index"));
    
    3、用orElseThrow替换 throw new Exception
        //原写法
        ProblemBLOBs problem = problemService.selectByPrimaryKey(id);
        if (problem == null){
            throw new PageException(PROBLEM_NOT_EXIST);
        }
        model.addAttribute("problem",problem);
        //新写法
        Optional<ProblemBLOBs> problem = Optional.ofNullable(problemService.selectByPrimaryKey(id));
        // 使用抛出异常
        model.addAttribute("problem", problem.orElseThrow(() -> new PageException(PROBLEM_NOT_EXIST)));
    4、方法的返回值最好也能用Optional包装,这样调用方也好判断是否为空

    使用要点:

    1.尽量避免使用get()方法

      第一条建议中直接调用get()方法是很危险的做法,如果Optional的值为空,那么毫无疑问会抛出NullPointerException异常,而为了调用get()方法而使用isPresent()方法作为空值检查,这种做法与传统的用if语句块做空值检查没有任何区别

        下面是get方法的源码,当值为null的时候,会抛出异常,这和我们使用该类方法的目的冲突,我们的目的就是尽可能消灭异常.
    
         public T get() {
    
                if (value == null) {
    
                    throw new NoSuchElementException("No value present");
    
                }
    
                return value;
    
         }
    
        // 这样和null判断没什么区别  最好别这么用 
    
        Optional<String> str = Optional.of("Hello world");
    
                if (str.isPresent()){
    
                    str.get();
    
                }

           第二条建议避免使用Optional作为实体类的属性,它在设计的时候就没有考虑过用来作为类的属性,如果你查看Optional的源代码,你会发现它没有实现java.io.Serializable接口,这在某些情况下是很重要的(比如你的项目中使用了

      某些序列化框架),使用了Optional作为实体类的属性,意味着他们不能被序列化。

    2.尽量避免使用isPresent()方法

    3. 避免使用Optional类型声明实体类的属性; 不要作为类的实例属性 Optional是容器

    4.不要作为方法参数

      

    1.尽量避免使用get()方法

  • 相关阅读:
    题目1009:二叉搜索树
    腾讯云API 生成Authentication Header加密字符串 C#代码示例
    《神经网络与深度学习》
    《神经网络与深度学习》第一章 使用神经网络来识别手写数字(三)- 用Python代码实现
    Rust语言的多线程编程
    C# DataTable的Select()方法不支持 != 判断
    《神经网络与深度学习》第一章 使用神经网络来识别手写数字(二)- 用梯度下降来训练学习
    C# 对多个文件进行zip压缩
    《神经网络与深度学习》:第一章 使用神经网络来识别手写数字(一)
    谷歌浏览器如何查看或获取Cookie字符串
  • 原文地址:https://www.cnblogs.com/hahajava/p/12191206.html
Copyright © 2020-2023  润新知