객체의 값이 비었거나 null인가?(isEmpty)

Velocity를 사용하면서 특정 객체가 비었는지(null, 빈문자열, 빈 배열, 빈 컬렉션) 확인할 필요가 자주 있어서 만들어 보았다.

JSTL을 사용한다면 empty 연산자로 쉽게 할 수 있다. 딴건 별거 없는데, 배열 검사하는 것만 좀 헷갈린다.

    import java.lang.reflect.Array;
    import java.util.Collection;
   
     /**
           * Null이거나 빈값(빈 문자열, 빈 컬렉션)인지 검사
           *
           * @param object
           * @return
           */
          @SuppressWarnings("unchecked")
          public boolean isEmpty(Object object) {
              if (object == null) {
                  return true;
              }

              if (object instanceof String) {
                  String str = (String) object;
                  return str.length() == 0;
              }

              if (object instanceof Collection) {
                  Collection collection = (Collection) object;
                  return collection.size() == 0;
              }

              if (object.getClass().isArray()) {
                  try {
                      if (Array.getLength(object) == 0) {
                          return true;
                      }
                  } catch (Exception e) {
                      //do nothing
                  }
              }

              return false;
          }
   ...

by 권남 | 2007/10/29 22:37 | 프로그래밍 | 트랙백 | 덧글(2)

트랙백 주소 : http://kwon37xi.egloos.com/tb/3460194
☞ 내 이글루에 이 글과 관련된 글 쓰기 (트랙백 보내기) [도움말]
Commented at 2007/10/31 10:44
비공개 덧글입니다.
Commented by 웃자환하게 at 2008/08/07 00:40
저 메쏘드 하나면 객체의 null 체크와 컬렉션 객체의 empty 체크를 한꺼번에...할 수 있겠네요.

:         :

:

비공개 덧글

◀ 이전 페이지          다음 페이지 ▶