欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

android中优雅的处理nullPointException(java8 Optional)

程序员文章站 2024-03-14 17:40:28
...

 今天和大家一起使用java8中的Optional API解决nullPointException,
先来看一段代码:


    public class Car {
        private Insurance insurance;
        public Insurance getInsurance() {
            return insurance;
        }
    }


    public class Insurance {
        private String name;
        public String getName() {
            return name;
        }
    }


    public class Person {
        private Car car;
        public Car getCar() {
            return car;
        }
    }

    public String getCarInsuranceName(Person p){
        return p.getCar().getInsurance().getName();
    }

这个getCarInsuranceName()方法一看就知道可能有nullPointException
通常我们这样处理:

public String getCarInsuranceName(Person p){
  if(p!=null){
    Car car = p.getCar();
    if(car!=null){
       Insurane insurance = car.getInsurance();
       if(insurance!=null){
          return insurance.getName();
       }
    }
  }
  return "Unknow";
}

好了,我们来看看优雅的程序员:

android中优雅的处理nullPointException(java8 Optional)

是看代码不是图

public class Person {
    private Optional<Car> car;
    public Optional<Car> getCar() {
        return car;
    }
}

public class Car {
    private Optional<Insurance> insurance;
    public Optional<Insurance> getInsurance() {
        return insurance;
    }
}

public class Insurance {
    private String name;
    public String getName() {
        return name;
    }
}

 public String getCarInsuranceName(Optional<Person> person) {
        return person.flatMap(Person::getCar)
                     .flatMap(Car::getInsurance)
                     .map(Insurance::getName)
                     .orElse("Unknown");
}

一脸懵逼有没有?好的大王,不管你有没有被征服,反正我是被臣妾是要开始
娓娓道来了。

上面的getCarInsuranceName方法的几个关键点:
1:使用lambda表达式(不会的请恶补上篇文章)
2:使用java.util.Optional对Person类中的Car类和Car类中的Insurance类包装
3:使用java.util.Optional 中流式API处理数据(类似rxjava或者java.util.steam)
官方文档https://docs.oracle.com/javase/8/docs/api/

偷偷的把optional类实例方法截了图

android中优雅的处理nullPointException(java8 Optional)


Optional构造函数


1:空值Optional
  Optional<Car> optCar = Optional.empty();
2:非空值Optional,传空抛异常
  Optional<Car> optCar = Optional.of(car);
3:可接受null的Optional
  Optional<Car> optCar = Optional.ofNullable(car);


使用map从Optional中取值和转换值


 Optional<Insurance> optInsurance = Optional.ofNullable(insurance);
 Optional<String> name = optInsurance.map(Insurance::getName);

使用flatMap转换optional


Optional<Car> optCar= person.flatMap(Person::getCar);
Optional<Insurance> = optCar.flatMap(Car::getInsurance)

map和flatMap区别:


Optional<Optional<Car>> car = optPerson.map(Person::getCar);
Optional<Car> car1 = optPerson.flatMap(Person::getCar);

ifPresent:如果值存在就会执行回调,否则什么也不干


optCar.ifPresent(Car::getInsurance);
 


isPresent:值存在返回true,否则false


boolean = optCar.isPresent;

 

orElse:有值则返回,否则返回一个默认值


String name = optCar.map(Insurance::getName)
                     .orElse("Unknown");
 

andThen,再来个filter的例子

    @RequiresApi(api = Build.VERSION_CODES.N)
    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.setProperty("a", "5");
        properties.setProperty("b", "-1");
        properties.setProperty("c", "true");
        System.out.println(readDuration(properties,"a"));
        System.out.println(readDuration(properties,"b"));
        System.out.println(readDuration(properties,"c"));
        OptionalInt.of(1).
    }
    @RequiresApi(api = Build.VERSION_CODES.N)
    public static int readDuration(Properties properties, String name) {
        return Optional.ofNullable(properties.getProperty(name))
                .flatMap(s -> parseString(s))
                .filter(i -> i > 10)
                .orElse(0);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public static  Optional<Integer> parseString(String s) {
        Optional<Integer> optionalInt;
        try {
            optionalInt = Optional.of(Integer.parseInt(s));
        } catch (NumberFormatException e) {
            optionalInt = Optional.empty();
        }
        return optionalInt;
    }

好了,通过上面的这些例子可以帮助我们更优雅的处理nullPointException,祝福各位撸的愉快

兼容低版本(<API 25)


不要担心,宝宝已经帮你完成了,只要下载我打好的jar包
https://download.csdn.net/download/qq_35599978/10569424  
Optional类由之前导入,java.util.function包替换为导入com.example.rxjavademo.util

 

上一篇: Java 8 新特性

下一篇: Java加解密