User user = null; //jdk7 if(user!=null){ User user = new User(); } //jdk8 User user = Optional.ofNullable(user).orElse(new User()); //jdk7 public String getCity(User user) throws Exception{ if(user!=null){ if(user.getAddress()!=null){ Address address = user.getAddress(); if(address.getCity()!=null){ return address.getCity(); } } } throw new Excpetion("取值错误"); } //jdk8 public String getCity(User user) throws Exception{ return Optional.ofNullable(user) .map(u-> u.getAddress()) .map(a->a.getCity()) .orElseThrow(()->new Exception("取指错误")); }