java 8 optional
程序员文章站
2022-03-04 10:52:08
...
例子:
类:
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
一、之前对空的判定
@Test
public void testOpt() {
User u = new User();
u.setName("hy");
if (u != null && u.getName() != null) {
System.out.println(u.getName());
}
}
二、使用optional对空的判定
@Test(expected = MyException.class)
public void testOpt() {
User s = new User();
s = null;
Optional<User> opt = Optional.ofNullable(s);
String name = opt.map(user -> user.getName()).orElseThrow(()-> new MyException("异常"));
//Assert.assertEquals("hy", name);
System.out.println(name);
}
自定义异常:
public class MyException extends RuntimeException {
MyException() {
}
MyException(String mgs) {
super(mgs);
}
}
上一篇: Java 8 Optional test