繁体   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