본문 바로가기
Spring/Spring

StringUtils.isEmpty() is deprecated 대체

by 작은돼지 2023. 1. 3.

 

문자열 null 체크 또는 빈 문자열임을 확인해주는 isEmpty 메서드는

Spring Framework 5.3 버전부터 deprecated되었다.

이에 따라 소스에서도 isEmpty 대신 hasText 또는 hasLength를 사용할 것을 권장하고 있다.

Deprecated
as of 5.3, in favor of hasLength(String) and hasText(String) (or ObjectUtils.isEmpty(Object))
	@Deprecated
	public static boolean isEmpty(@Nullable Object str) {
		return (str == null || "".equals(str));
	}​

hasLength: null이 아니면서 길이가 0보다 큰 지
	public static boolean hasLength(@Nullable String str) {
		return (str != null && !str.isEmpty());
	}​

hasText: null이 아니면서 비어있지 않고, 공백을 제외한 텍스트가 있는 지
	public static boolean hasText(@Nullable String str) {
		return (str != null && !str.isEmpty() && containsText(str));
	}

	private static boolean containsText(CharSequence str) {
		int strLen = str.length();
		for (int i = 0; i < strLen; i++) {
			if (!Character.isWhitespace(str.charAt(i))) {
				return true;
			}
		}
		return false;
	}​

정리
isEmpty: 사용 자제, Object를 파라미터로 받았었기 때문에 혼란이 있었던 것 같음
hasLength: null이 아니고 빈 문자열을 허용할 경우에 사용
hasText: 텍스트가 반드시 있어야 할 때 사용

https://github.com/spring-cloud/spring-cloud-zookeeper/issues/274

 

Replace usage of deprecated StringUtils.isEmpty with !StringUtils.hasLength · Issue #274 · spring-cloud/spring-cloud-zookeeper

As of Spring 5.3 StringUtils.isEmpty is deprecated. The official migration hint is to either use one of the following: !StringUtils.hasLength !StringUtils.hasText To keep behaviour exactly the way ...

github.com