英文:
How to check the variables of an Object are Empty or NULL in JAVA?
问题
如何在JAVA中检查“对象的变量”是否为空或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);
}
而不是使用“NULL”,我正在尝试创建一个新的Employee对象
Employee employee = repository.getEmployee(id).orElseGet(new Employee());
if (employee.isEmpty()) { //--------- 如何做??????
employee = new Employee();
employee.id(1);
employee.name("Thirumal");
employee.mobile("+91-8973-697-871");
repository.save(employee);
}
如何检查“对象的成员”是否为空/NULL?
英文:
How to check variables of Objects
are empty or NULL
in JAVA?
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);
}
Instead of NULL
, I am trying to create an object new Employee()
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);
}
How to check the member of objects
are empty/NULL
?
答案1
得分: 1
只需将 isEmpty
方法添加到 Employee
类中并在那里实现,或者使用 null 对象模式 代替 new Employee()
。
至于您在代码中实际要做的事情,我建议像这样做:
Employee employee = repository.getEmployee(id).orElseGet(() -> {
Employee emp = new Employee();
emp.setId(1);
emp.setName("Thirumal");
emp.setMobile("+91-8973-697-871");
return repository.save(emp);
});
英文:
Just add that isEmpty
method to Employee
class and implement it there, or use a null object pattern instead of doing new Employee()
.
As to what you are actually trying to do in your code, I suggest to do it like that instead:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-java -->
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);
});
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论