본문
enum 활용(JAVA)
프로그래밍/Java 2016. 10. 1. 16:44
반응형
# enum sample source
enum을 사용하여 코드 재사용성, 가독성을 높인다.
source01) Main.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | package com.source.common._enum; import com.source.common._enum.Constants.COMMAND_TYPE; import com.source.common._enum.Constants.MESSAGE_TYPE; public class Main { public static void main(String[] args) { System.out.println("STOP Code : " + COMMAND_TYPE.STOP.getTypeCode()); System.out.println("REQ_ACK Code : " + MESSAGE_TYPE.REQ_ACK.getTypeCode()); } } | cs |
source02) Constants.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | package com.source.common._enum; public class Constants { public enum COMMAND_TYPE { GO("01"), STOP("02"), READY("03"); private String typeCode; private COMMAND_TYPE(String typeCode) { this.typeCode = typeCode; } public String getTypeCode() { return this.typeCode; } public COMMAND_TYPE getItem(String typeCode) { for (COMMAND_TYPE fc : COMMAND_TYPE.values()) { if (fc.typeCode.equals(typeCode)) { return fc; } } return null; } } public enum MESSAGE_TYPE { REQ_ACK("0"), REQ_NON_ACK("1"), SUCCESS_RESPONSE("2"), BAD_RESPONSE("4"); private String typeCode; private MESSAGE_TYPE(String typeCode) { this.typeCode = typeCode; } public String getTypeCode() { return this.typeCode; } public MESSAGE_TYPE getItem(String typeCode) { for (MESSAGE_TYPE fc : MESSAGE_TYPE.values()) { if (fc.typeCode.equals(typeCode)) { return fc; } } return null; } } // You can define another enum .. } | cs |
result)
1 2 3 | STOP Code : 02 REQ_ACK Code : 0 | cs |
반응형
댓글