BeanUtils.copy Properties 속성 을 복사 할 때 빈 값 을 무시 합 니 다.
spring 을 사용 하여 개발 한 사람 은 이 코드 가 낯 설 지 않 을 것 입 니 다.DTO,VO,PO 간 의 복사 에 자주 사 용 됩 니 다.
/**
* copy
*
**/
BeanUtils.copyProperties(Object source, Object target)
그러나 이 줄 코드 는 모든 속성 을 copy 로 합 니 다.어떤 때 는 개별 속성 을 복사 하지 않 으 려 고 합 니 다(예 를 들 어 null 값 속성).이 때 는 다른 방법 이 필요 합 니 다.
/**
* copy
*
**/
BeanUtils.copyProperties(Object source, Object target, String... ignoreProperties)
세 번 째 매개 변 수 는 가 변 길이 형식 입 니 다.동적 으로 무시 하 는 속성 을 가 져 옵 니 다.
/**
*
*
* @param source
* @return
*/
public static String[] getNullPropertyNames (Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<>();
for(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);
}
확장:맵 과 Bean 사 이 를 바 꾸 고 두 가지 방식 을 제공 해 야 할 때 가 많 습 니 다.
1.fastjson 사용
1.맵 전환 bean:
Map paramMap = new HashMap();
String jsonStr = JSONObject.toJSONString(paramMap);
Object infoDo = JSON.parseObject(jsonStr, Object.class);
2,bean 맵 전환:Map
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Apache BeanUtilsBean 의 copy Properties 를 이용 하여 대상 속성 값 copy!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.