输入工作人员ID时,我想获取护士的姓名,工作人员班级中可以有医生,也可以有护士的;例如,如果staffID等于1,则它将是医生而不是护士,但是当我这样做时护士ID相同,它会返回空指针错误。
staff.getNurse().getLastName();
返回空指针错误
The get nurse command in the staff class
public Nurse getNurse() {
return nurse;
}
创建员工
public Staff(Doctor doctor, Nurse nurse){
this.doctor = doctor;
this.nurse = nurse;
}
护士只是一个具有基本字段的类,例如名字和姓氏都存储为字符串
我想检查员工在哪里是护士或医生,如果是,请获取他们的姓名并将其设置为NurseDocName并将其工作标题设置为字符串标题
Staff staff = new Staff();
//staffID is set via an input from a JTextarea
staff = sM.getStaff(staffID);
String nurseDocName = "";
String title = "Nurse ";
if(staff.getDoctor().equals(null)) nurseDocName = staff.getNurse().getLastName();
else
{
nurseDocName = staff.getDoctor().getLastName();
title = "Doctor ";
}
在我的会话管理器休眠类中获取职员方法
public Staff getStaff(Integer staffID){
Session session = factory.openSession();
Transaction tx = null;
Staff staff = new Staff();
try {
tx = session.beginTransaction();
staff = session.get(Staff.class, staffID);
}catch (HibernateException e){
if(tx != null) tx.rollback();
}
session.close();
return staff;
}
解决方案将.equals更改为==
if(staff.getDoctor() == null) nurseDocName = staff.getNurse().getLastName();