Java enum Examples
Enum Type
보통 열거형이라고 합니다. String 클래스와 마찬가지로 불변의 객체이기도 합니다. 상수의 집합을 만들거나 특정 객체의 상태를 모아서 열거형으로 만들면 코드의 가독성이 좋아질 수 있습니다.
Java enum Examples
간단하게 자바 enum에 대해 코드로 살펴봅시다.
The basic enum usage
기본적인 enum 사용법입니다.
import org.junit.Test;
public class EnumTest {
/** Case 1. The basic enum usage */
public enum Person {
JDM, LHR
}
@Test
public void testPerson(){
Person person = Person.JDM;
/**
* .name() method return value is "enum constant name".
*/
System.out.println(person.name()); // print 'JDM'
/**
* .ordinal() method return value is "index order".
*/
System.out.println(person.ordinal()); // print '0'
}
}
The complex usage on short syntax enum
enum에 추가적인 필드를 구성하고 싶으면 아래처럼 사용합니다.
import org.junit.Test;
public class EnumTest {
/** Case 2. The complex usage on short syntax enum */
public enum CommandEnum {
START("start", "opt"),
STOP("stop", "opt"); // watch out. need semi-colon.
private String command;
private String opt;
CommandEnum(String command, String opt){
this.command = command;
this.opt = opt;
}
public String getCommand(){ return this.command; }
public String getOpt(){ return this.opt; }
}
@Test
public void testCommandEnum(){
CommandEnum commandEnum = CommandEnum.START;
switch( commandEnum ) {
case START:
System.out.println(commandEnum.name()); // print 'START'
System.out.println(commandEnum.getCommand()); // print 'start'
System.out.println(commandEnum.getOpt()); // print 'opt'
// do something...
break;
case STOP:
// do something...
break;
}
// do something...
}
}