2017-05-05 15 views
1

소스 bean에서 대상 bean으로 일부 특성을 복사하기 위해 Apache Commons BeanUtils를 사용하고 있습니다. 이 경우 소스 bean에서 오는 목적지 bean에 null 값을 설정하고 싶지 않습니다. 예를 들어처럼BeanUtils.copyProperties에서 null 값을 무시하십시오.

:

Person sourcePerson = new Person(); 
sourcePerson.setHomePhone("123"); 
sourcePerson.setOfficePhone(null); 

Person destPerson = new Person(); 
destPerson.setOfficePhone("456"); 

BeanUtils.copyProperties(destPerson, sourcePerson); 
System.out.println(destPerson.getOffcePhone()); 

// 여기 destPerson OfficePhone과는 내가이 문제를 방지하려면 어떻게해야

를 null로 설정됩니다? 나는 심지어 아래의 성명을 씌우려고 노력했다 : BeanUtilsBean.getInstance().getConvertUtils().register(false, false, 0);

도움이되지 않는 것.

어쨌든 Apache Commons BeanUtils에서 null을 제외 할 수 있습니까?

+0

http://stackoverflow.com/questions/17417345/beanutils-copyproperties-api-to-ignore-null-and-specific-propertie – StanislavL

+0

속성을 변환하지 않을 PropertyUtils를 사용할 수 있습니다. 그렇지 않으면 ConvertUtils.register를 기본값으로 등록해야합니다 ... – VelNaga

+0

기본값을 원하지 않습니다. 기존 값을 null로 대체하고 싶지 않습니다. 나는 아직도 PropertyUtils가 null을 어떻게 제외하는지 알지 못한다. –

답변

0

Apache Commons BeanUtils는이 상황을 지원하지 않습니다. 그래서 당신은 당신의 각자하여이 작업을 수행해야한다 : 속성이 contact.businessName.firstname로 문자열을 같은 firstName을 어디에 중첩 및 기타 사용자 정의 클래스입니다 때

public class BeanUtils { 

    public static void copyPropertiesIgnoreNull(Object source, Object dest) { 
     final BeanWrapper src = new BeanWrapperImpl(source); 
     java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors(); 
     for(java.beans.PropertyDescriptor pd : pds) { 
      if(!src.isReadableProperty(pd.getName()) || pd.getWriteMethod() == null){ 
       continue; 
      } 
      Object srcValue = src.getPropertyValue(pd.getName()); 
      if (srcValue == null) { 
       continue; 
      } 
      BeanUtils.copyProperties(dest, pd.getName(), srcValue); 
     } 
    } 
} 
+0

이 기능을 사용하려면 어떤 패키지/버전을 사용하고 있습니까? 'BeanUtils.copyProperties (dest, pd.getName(), srcValue);' – JustOneMoreQuestion

1

BeanUtils이 작동하지 않습니다.