如何在JAVA中检查variables of Objects
是empty or NULL
?
Employee employee = repository.getEmployee(id).orElseGet(null);
if (employee == null) {
employee = new Employee();
employee.id(1);
employee.name("Thirumal");
employee.mobile("+91-8973-697-871");
repository.save(employee);
}
我正在尝试创建一个对象new Employee()
,而不是NULL
Employee employee = repository.getEmployee(id).orElseGet(new Employee());
if (employee.isEmpty()) { //--------- How to do ????????
employee = new Employee();
employee.id(1);
employee.name("Thirumal");
employee.mobile("+91-8973-697-871");
repository.save(employee);
}
如何检查member of objects
是empty/NULL
?
只需将isEmpty
方法添加到Employee
类中并在那里实现它,或者使用null对象模式而不是执行new Employee()
。
至于你实际上想在代码中做什么,我建议你这样做:
Employee employee = repository.getEmployee(id).orElseGet(() -> {
Employee emp = new Employee();
emp.id(1);
emp.name("Thirumal");
emp.mobile("+91-8973-697-871");
return repository.save(emp);
});