2017년 7월 6일 목요일

StringUtils의 isEmpty, isBlank 분석.

자바에서 Null 포함 빈값을 체크 할 때, StringUtils의 isEmpty 나 isBlank를 사용한다.
isEmpty는 "", null 일 경우 true를 리턴한다.
isBlank는 "", null, " " 일 경우 true를 리턴한다.

해당 메소드가 어떻게 동작하는 지 알아 봤다.

소스
isEmpty가 동작하는 방식은 간단하다.
        public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}

null 이거나, length 가 0 일경우를 체크 한다.

 

 

isBlank는 조금 더 복잡하다.
        public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}

첫번째는 isEmpty와 같지만 스페이스를 체크하기 위해 for문을 돈다.

 

 

간혹 StringUtils 라이브러리가 없고, 추가 할 수 없는 경우 참고 하면 좋을 것 같다.

댓글 없음:

댓글 쓰기