簡體   English   中英

如何 null 以通用方式檢查並返回值

[英]How to null check and return a value in a generic way

我有一長串 object 映射要從 JAXB 自動生成的類中執行。

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

基本上我需要對所有字段進行 null 檢查:

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

問題是這些太多了,它們都有不同的類型:RentalCustomerIDType、TradingType、VatNumberType..etc

是否有一種優雅的方法可以通過創建一個GENERIC方法使 null 檢查並為ALL返回正確的值,可能使用 Java 的功能庫?

也許在 class 生成時使用反射並通過為字段分配非空值來消除所有空值?

檢查替換多個變量中的 null 值 java

他們說(回答的人)他們強烈反對為此目的使用反射……但是……嗯。 我已經做到了並且有效。

您可以使用通用方法聲明getValueFromAllObjects方法,然后使用反射調用getValue方法

public static <T> String getValueFromAllObjects(T t) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
  if(t != null){
    return (String) t.getClass().getDeclaredMethod("getValue").invoke(t);
  }
  else {
   return "";
 }
}

有關反射替代方案,請參閱https://stackoverflow.com/a/54883454/442256 我剛剛在上面的代碼中內聯了一個示例

據我了解,您不想更改現有的自動生成的類。 您可以做的是創建一個CustomerWrapper class,它包裝Customer並在null設置為字段時插入默認值。 這是代碼中的想法:

public class CustomerWrapper() {

    private final Customer customer;

    public CustomerWrapper(Customer customer) {
        this.customer = customer;
    }

    public void setCustomerId(String id) {
        this.customer.setCustomerId(id == null ? "" : id);
    }

    // Insert other methods here.

}

這做你想要的。 但有一個警告。 每種類型都必須實現提供getValue()方法的相同接口。 否則,您可能需要反思才能獲得您懷疑的方法。 但這是后代的解決方案。

setType(rentalSearchCustomer::getCustomerid,
        customer::setCustomerId);
setType(rentalSearchCustomer::getTradingname,
        customer::setCustomerName);
setType(rentalSearchCustomer::getVatNumber,
        customer::setVatNumber);
System.out.println(customer);
        
    
    
public static <T extends GetValue> void setType(Supplier<T> sup,
        Consumer<String> con) {
    if (sup.get() == null) {
        con.accept("");
    } else {
        con.accept(sup.get().getValue());
    }
}
    
interface GetValue {
    public String getValue();
}

我猜你想使用類似的東西。 在這里,我將 ResponseUserDto 作為我的 Pojo Class 以對其屬性進行 null 檢查。

private ResponseUserDto getValidNotNullPropertyObject(Object source) {
    final BeanWrapper src = new BeanWrapperImpl(source);
    Map < String, Object > result = new HashMap<>();
    for (PropertyDescriptor property: src.getPropertyDescriptors()) {
        if (src.getPropertyValue(property.getName()) == null) {
            /* if(property.getPropertyType() == ?) {
                    //maybe do somethig here
                }*/
            result.put(property.getName(), ""); // this is start
        } else {
            result.put(property.getName(), src.getPropertyValue(property.getName()));
        }
    }
    final ObjectMapper mapper = new ObjectMapper(); // Jackson's ObjectMapper
    final ResponseUserDto finalResult = mapper.convertValue(result, ResponseUserDto.class);
    return finalResult;
}

要使用它,你可以這樣稱呼它

return this.getValidNotNullPropertyObject(responseUserDto);

也許是面向方面編程的一個案例,如果它的使用是一個選項:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM