java8 回撥新寫法和空指標處理
阿新 • • 發佈:2019-02-16
@FunctionalInterface
public interface IPlay {
String show(String msg);
default String make(){
return "make";
}
}
public class Person { private String userName; private String password; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
import java.util.Optional; public class Main { public static void main(String[] args) { IPlay play1 = new IPlay() { @Override public String show(String msg) { return "原來的寫法如下"; } }; // 現在的寫法 IPlay play = (msg)->{return msg;}; String msg = play.show("我是訊息"); System.out.println(msg); msg = play.make(); System.out.println(msg); // Optional 更多的體現是一個容器,包含null的一個容器。通過他去判斷。 Person person = null; Optional<Person> optional = Optional.ofNullable(person); boolean flag = optional.isPresent(); System.out.println(flag); if (flag){ person = optional.get(); // 獲取物件進行處理。 System.out.println(person); }else{ System.out.println("person is null"); } } }