java8 Optional用法
程序员文章站
2022-03-04 11:35:05
...
1、准备对象
package org.example.note.global.pojo;
import lombok.*;
import javax.validation.constraints.NotNull;
/**
* java 8
*
* @author admin
*/
// @Data
// @EqualsAndHashCode
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class User {
// alibaba规约:POJO类,全部使用包装类型(Integer、Long等)
// private long id;
private Long id;
@NotNull(message = "userName 不能为空")
private String userName;
private String password;
private String realName;
// private int age;
private Integer age;
public User(String userName) {
this.userName = userName;
}
}
2、用法测试用例
package org.example.note;
import org.example.note.global.pojo.User;
import org.junit.Test;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
/**
* @Author xiaoming-mac
* @Date 2021/6/24
* @Version 1.0
*/
public class OptionalTest {
User user = null;
User user1 = new User();
List<User> userList = null;
/**
* 错误示例
*/
@Test(expected = NullPointerException.class)
public void expectedTest() {
String a = Optional.ofNullable(user.getUserName()).orElse(null);
}
/**
* 避免对象空指针
*/
@Test
public void ofNullableObjectTest() {
User res = Optional.ofNullable(user1).orElse(new User());
System.out.println(res.getAge());
}
/**
* 避免对象空指针,获取属性
*/
@Test
public void ofNullableAttributeTest() {
String userName = Optional.ofNullable(user).map(User::getUserName).orElse("default name");
}
/**
* 避免集合判空时空指针
*/
@Test
public void ListEmptyTest() {
List<User> users = Optional.ofNullable(userList).orElse(Collections.emptyList());
// 判断集合是否为空
System.out.println(users.isEmpty());
}
/**
* 测试效率
*/
@Test
public void orElseGetTest() {
// 非空,会执行后续函数(影响效率)
User res1 = Optional.ofNullable(user1).orElse(createUser());
// 非空,不会执行后续函数
User res2 = Optional.ofNullable(user1).orElseGet(this::createUser);
User res3 = Optional.ofNullable(user1).orElseGet(User::new);
}
private User createUser() {
User user = new User();
user.setUserName("create user");
System.out.println(user);
return user;
}
}
上一篇: elementui table表格 点击行实现高亮
下一篇: ElementUi rules表单验证