2008/07/25 09:16 Developer
Enum클래스 비교구문과 주의사항
Enum클래스를 사용하면 잘못된 타입에 대한 걱정을 줄일수가 있다.
나는 이미 여러곳에서 사용을 하고 있고 jdk5.0을 사용하는 대부분의 사람들이 사용을 할 것이다.
Enum클래스를 사용하면 타입이 같은지 비교를 하는 표현을 자주 쓴다.
비교하는 문장을 쓸때 여러가지 표현을 적어보자.
RelationType이라는 enum클래스를 잠깐 살펴보자.
public enum RelationType {
/** 로그인 하지 않은 사용자 */
GUEST_USER (4),
.........................................
/** 블로그 주인 */
BLOG_OWNER(0);
private Integer type;
private RelationType(Integer type) {
this.type = type;
}
public Integer getType() {
return type;
}
}
다음과 같은 메소드를 구현하려고 한다.
public boolean isBlogOwner() ;
여러가지 방법으로 구현을 할수가 있다. 아래 방법은 모두 정상적으로 작동을 하는 방법이지만, 나는 3번이나 4번을 선호한다. 코드가 짧기도 하고 enum클래스의 특성을 가장 잘 살릴수 있는 코드이기때문이다.
1.
return getRelationType() != null && getRelationType() == RelationType.BLOG_OWNER;
}
2.
return getRelationType() != null && getRelationType().equals(RelationType.BLOG_OWNER);
}
3.
return RelationType.BLOG_OWNER.equals(getRelationType());
}
4.
return RelationType.BLOG_OWNER == getRelationType());
}
다음에 테스트는 놀랍게도(?) 통과를 한다. getType()은 Integer라는 래퍼클래스인데, 왜 통과를 했을까?
assertFalse(new Integer(4) == new Integer(4));
assertTrue(RelationType.BLOG_OWNER.getType() == RelationType.BLOG_OWNER.getType());
assertTrue(RelationType.GUEST_USER.getType() == RelationType.GUEST_USER.getType());
}
enum은 메모리상에서 static하게 하나만 존재를 한다는 것을 알수가 있다.
* 관련문서
http://www.ologist.co.kr/624
http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Enum.html