[Java] StringUtils 사용법

devdo·2022년 5월 4일
2

Java

목록 보기
46/56

org.apache.commons.lang의 StringUtils 클래스는 따로 의존성을 디팬더시를 해주어야 한다.

기본적으로 null-safe 한 연산을 해주기 때문에 아주 유용하고 기본 String에는 없는 유용한 메서드들이 있다. (최근에 repeat(java 11) 같은 메서드들도 String에 기본으로 들어가 있긴 하지만 그래도 유용하다.)

implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.12.0'

or)

또는 Spring framework에서 기본으로 제공해준다.
위의 apache보단 기능이 부족하지만 그래도 어차피 사용하는 spring에만 의존적이기 때문에 유용할 경우가 많다.

import org.springframework.util.StringUtils;

StringUtils 클래스는 자바의 String 클래스가 제공하는 문자열 관련 기능을 강화한 클래스라 보면 된다.


유용한 메서드들

1) isEmpty()
: null체크도 해주고, 길이가 0이 아닌지 체크
이것보다 StringUtils를 쓸 때는 hasText()를 권한다.

이 메서드를 사용할 때는

  • 꼭 String이 아닌 객체를 null 체크를 하고 싶을 때 ex) Long, Integer
  • ObjectUtils를 쓸 때
	public static boolean isEmpty(@Nullable Object str) {
		return (str == null || "".equals(str));
	}

2) hasText()
: 문자열 유효성 검증 유틸 메소드

null 인 것,
길이가 0인 것,
공백("" or " ")인 것

이 문자열에 하나라도 포함되었다면 false이다.

어쨋든 둘 다 파라미터 값으로 null을 주더라도 절대 NullPointException을 발생시키지 않는다!
(null이 입력되는 경우, 메소드에 따라 알맞은 결과를 리턴.)

StringUtils.hasText(String)	// boolean

StringUtils.containsText(CharSequence)	// boolean

안에 내부를 보면 이런 내용이다.

	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;
	}


참고

profile
배운 것을 기록합니다.

0개의 댓글