Java:如何忽略具有 null 的字段并仅通过修改后的属性传递

标签 java spring spring-mvc

我编写了一个更新方法,它接受修改的字段。

 public ResponseEntity<String> updateProduct(@RequestBody final Product product)
 {
  returnValue = productService.updateProduct(product);
 }

Product是一个bean类,拥有50个属性列表。从 UI 中,如果我修改 5 个字段,它会将这些修改的字段和其他属性保留为 null。这里如何进行过滤呢?我只想传递更新后的值

 returnValue = productService.updateProduct(product); 

最佳答案

如果没有看到 Product 类或 ProductService.updateProduct 方法中的任何代码,就很难说。不过,您也许可以使用 Apache Commons 库中提供的 BeanUtilsBean 类。

public static void nullAwareBeanCopy(Object dest, Object source) throws IllegalAccessException, InvocationTargetException {
    new BeanUtilsBean() {
        @Override
        public void copyProperty(Object dest, String name, Object value)
                throws IllegalAccessException, InvocationTargetException {
            if(value != null) {
                super.copyProperty(dest, name, value);
            }
        }
    }.copyProperties(dest, source);
}

这是我写的,但由于您使用 spring,您可能需要使用位于 org.springframework.beans.BeanUtils 的 spring bean utils 类。快速搜索该代码时我发现了 this answer from alfredx其中有这个代码

public static String[] getNullPropertyNames (Object source) {
    final BeanWrapper src = new BeanWrapperImpl(source);
    java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

    Set<String> emptyNames = new HashSet<String>();
    for(java.beans.PropertyDescriptor pd : pds) {
        Object srcValue = src.getPropertyValue(pd.getName());
        if (srcValue == null) emptyNames.add(pd.getName());
    }
    String[] result = new String[emptyNames.size()];
    return emptyNames.toArray(result);
}

// then use Spring BeanUtils to copy and ignore null
public static void myCopyProperties(Object, src, Object target) {
    BeanUtils.copyProperties(src, target, getNullPropertyNames(src))
}

然后您可以像这样使用它:

public void updateProduct(Product updatedProduct) {
    Product existingProduct = /*find existing product*/;
    nullAwareBeanCopy(existingProduct, updatedProduct);
    // or 
    myCopyProperties(updatedProduct, existingProduct);
}

注意这两种不同的方法源/目标参数彼此相反。

关于Java:如何忽略具有 null 的字段并仅通过修改后的属性传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37407000/

相关文章:

java - ActiveMQ SSL 性能

java - 如何在 MongoDb 中更喜欢读取辅助文件

java - 生成的java代码格式化

Spring Boot 登录成功后重定向到当前页面

java - 返回到 Spring Batch 中的上一个步骤

java - 如何注入(inject)用户名(不是身份验证)?

java - ServletDispatcher 无法转换为我的 spring 项目中的 Javax.servlet.Servlet 异常

java - 在 SpringBoot 2.0.1.RELEASE 应用程序中读取文件

java - JMS 主题消息大小

java - 如何在 Spring Boot 应用程序中实现长轮询 REST 端点?