Java:如何忽略具有null且仅通过修改的属性传递的字段
我编写了一个更新方法,它接受修改的字段Java:如何忽略具有null且仅通过修改的属性传递的字段,java,spring,spring-mvc,Java,Spring,Spring Mvc,我编写了一个更新方法,它接受修改的字段 public ResponseEntity<String> updateProduct(@RequestBody final Product product) { returnValue = productService.updateProduct(product); } 很难说没有从Product类或ProductService.updateProduct方法中看到任何代码。但是,您可以使用Apache Commons库中提供的B
public ResponseEntity<String> updateProduct(@RequestBody final Product product)
{
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的Springbean utils类。正在快速搜索我遇到的包含此代码的代码
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 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);
}