如何检查JAVA中对象的变量是否为空或NULL?

huangapple go评论104阅读模式
英文:

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(() -&gt; {
   Employee emp = new Employee();
   emp.id(1);
   emp.name(&quot;Thirumal&quot;);
   emp.mobile(&quot;+91-8973-697-871&quot;);
   return repository.save(emp);
});

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年8月13日 17:08:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63391784.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定