最終更新: hira_kosukety 2017年04月18日(火) 10:59:31履歴
概要:Java の enum の使い方を学んだのでメモ
内容:
簡単な使い方
少しこった使い方
各項目に、ラベルと任意の値をセットする
内容:
簡単な使い方
public class sample1{ public enum emSAMPLE{ SAMPLE1, // 値1 SAMPLE2, // 値1 SAMPLE3, // 値1 SAMPLEX } }と定義して、
public class test1{ sample1.emSAMPLE emsample1; test1(){ emsample1 = sample1.emSAMPLE.SAMPLE1; /*「import」で「sample1.emSAMPLE」をインポートすれば クラス名は省略可能 */ emsample1 = emSAMPLE.SAMPLE1; } private void func1(){ if( emsample1==emSAMPLE.SAMPLE1 ){ /**/ }else if( emsample1==emSAMPLE.SAMPLE2 ){ /**/ } switch(emsample1){ case SAMPLE1: log.debug(""); break; // switch の case文では emSAMPLE は省略する。 case SAMPLE2: log.debug(""); break; case SAMPLE3: log.debug(""); break; } } private void func2(){ sample1.emSAMPLE emsample2 = emSAMPLE.SAMPLE2; func3(emsample2); } private void func3(emSAMPLE lsample){ /* メソッドの引数にする例 */ } }
少しこった使い方
各項目に、ラベルと任意の値をセットする
public class sample2{ public enum emSAMPLE{ SAMPLE1("sample1 test", 1), // 値1 SAMPLE2("sample2 test", 2), // 値2 SAMPLE3("sample3 test", 3), // 値3 SAMPLEX("sampleex test", 4) ; /* メンバ変数を定義 */ private String label; private int value; /* コンストラクタ */ emSAMPLE(String label, int value){ this.label = label; this.value = value; } /* getter */ public String getLabel(){ return this.label; } public int getValue(){ return this.value; } public static emSAMPLE getType(final int value){ for(emSAMPLE parts : emSAMPLE.values()){ if( parts.getValue() == value){ return parts; } } return null; } public static String getLabelOfGlobal(int value){ String label = ""; for(emSAMPLE parts : emSAMPLE.values() ){ if( parts.getValue() == value){ label = parts.getLabel(); break; } } return label; } } }と定義
public class test2{ sample2.emSAMPLE emsample2; test2(){ emsample2 = emsample2.emSAMPLE.SAMPLE1; /*「import」で「sample1.emSAMPLE」をインポートすれば クラス名は省略可能 */ emsample2 = emSAMPLE.SAMPLE1; } private void func1(int typeval){ emSAMPLE sample = emSAMPLE .getType(typeval); /* 引数とValueが一致する emSAMPLEを取得できる */ log.debug("emSAMPLE.getLabelOfGlobal(typeval)"); }こんな感じで、ログ出したり、使い道はご自由に
コメントをかく