Java/Component
[JAVA] isEmpty - null 혹은 비어있는지 비교 후 boolean
고플밍
2022. 3. 24. 17:31
공통 메서드 중 가장많이 사용하는 isEmpty 메서드를 소개한다.
null or not null 을 먼저 판별한 후
각 어떤 클래스인지 instanceof로 판단 뒤 각 클래스에 선언된 메서드를 이용하여 판별한다.
/**
* obj가 null 혹은 비어있는지 비교
*
* @params Object obj
* @return boolean
* @apiNote Custom.isEmpty(obj)
*
*/
public static boolean isEmpty(Object obj){
// null 이라면
if (obj == null)
return true;
// String 이라면
if (obj instanceof String)
return ("".equals(((String) obj).trim()));
// Map이라면
if (obj instanceof Map)
return ((Map<?,?>) obj).isEmpty();
// List라면
if (obj instanceof List)
return ((List<?>) obj).isEmpty();
// Object 배열이라면..
if (obj instanceof Object[])
return (((Object[]) obj).length == 0);
return false;
}