As you can see an example in the code below, I need to use a lot of if. Otherwise it throws null pointer exception.
if (despt.getDespatchSupplierParty().getParty().getContact() != null) {
if (despt.getDespatchSupplierParty().getParty().getContact()
.getTelephone() != null) {
tfdesp000_arch.setDcpPartyContactTelephone(despt.getDespatchSupplierParty()
.getParty().getContact().getTelephone().getValue());
}
if (despt.getDespatchSupplierParty().getParty().getContact().getTelefax() != null) {
tfdesp000_arch.setDcpPartyContactTelefax(despt.getDespatchSupplierParty()
.getParty().getContact().getTelefax().getValue());
}
if (despt.getDespatchSupplierParty().getParty().getContact()
.getElectronicMail() != null) {
tfdesp000_arch.setDspPartyContactElectronicMail(despt.getDespatchSupplierParty()
.getParty().getContact().getElectronicMail().getValue());
}
if (despt.getDespatchSupplierParty().getParty().getContact().getName() != null) {
tfdesp000_arch.setDspContactName(despt.getDespatchSupplierParty().getParty()
.getContact().getName().getValue());
}
}
How do I avoid this null pointer exception using few ifs.
You can write a single function which performs the null checks and reuse it:
Some of the types may be wrong here, as you haven't given the signatures of your methods. For instance, if
getValue
doesn't always returnString
, you can add another type parameter to thesetContactField
method: