Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

java - How to null check and return a value in a generic way

I have a long list of object mapping to do from classes auto generated by JAXB.

 customer.setCustomerId(rentalCustomer.getCustomerid().getValue()));
 customer.setCustomerName(rentalCustomer.getTradingname().getValue());
 customer.setVatNumber(rentalSearchCustomer.getVatNumber().getValue());
 ....
 ....

Basically I need to make a null check for ALL fields:

getValue(RentalCustomerIDType idType){
  if(idType != null){
    return idType.getValue();
  }
  else {
   return "";
 }
}

Problem is there are too many of these and they all have different types: RentalCustomerIDType, TradingType, VatNumberType..etc

Is there an elegant way to this by creating a GENERIC method that makes null check and return proper values for ALL maybe using Functional Libraries for Java?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Perhaps use reflection on the class when it's generated and eliminate all nulls by assigning non-null values to the fields?

Check an replace null values in multiple variables java

They say (the guy who answered) that they strongly disagree with using reflection for this purpose... but... meh. I've done it and it works.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...