简体   繁体   English

如何 null 以通用方式检查并返回值

[英]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.我有一长串 object 映射要从 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:基本上我需要对所有字段进行 null 检查:

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问题是这些太多了,它们都有不同的类型: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?是否有一种优雅的方法可以通过创建一个GENERIC方法使 null 检查并为ALL返回正确的值,可能使用 Java 的功能库?

Perhaps use reflection on the class when it's generated and eliminate all nulls by assigning non-null values to the fields?也许在 class 生成时使用反射并通过为字段分配非空值来消除所有空值?

Check an replace null values in multiple variables java 检查替换多个变量中的 null 值 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.我已经做到了并且有效。

You could use a generic method to declare the getValueFromAllObjects method and then use reflection to invoke the getValue method您可以使用通用方法声明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 "";
 }
}

Refer to https://stackoverflow.com/a/54883454/442256 for reflection alternatives.有关反射替代方案,请参阅https://stackoverflow.com/a/54883454/442256 I've just inlined an example in your code above我刚刚在上面的代码中内联了一个示例

From what I understand, you do not want to be changing existing auto-generated classes.据我了解,您不想更改现有的自动生成的类。 What you can do is create a CustomerWrapper class that wraps Customer and inserts defaults when a null is set to a field.您可以做的是创建一个CustomerWrapper class,它包装Customer并在null设置为字段时插入默认值。 This is the idea in code:这是代码中的想法:

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.

}

This does what you want.这做你想要的。 But there is a caveat.但有一个警告。 Each type must implement the same interface that provides the getValue() method.每种类型都必须实现提供getValue()方法的相同接口。 Otherwise, you will probably need reflection to get the method as you suspected.否则,您可能需要反思才能获得您怀疑的方法。 But here is a solution for posterity.但这是后代的解决方案。

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();
}

I guess you want to use something like.我猜你想使用类似的东西。 here I have taken ResponseUserDto as my Pojo Class for null checks of it's properties.在这里,我将 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;
}

and to use this, you can call it like this要使用它,你可以这样称呼它

return this.getValidNotNullPropertyObject(responseUserDto);

maybe a case for Aspect Oriented Programming, if its use is an option:也许是面向方面编程的一个案例,如果它的使用是一个选项:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM