1. 程式人生 > >enum 列舉型別定義常量及呼叫的應用舉例

enum 列舉型別定義常量及呼叫的應用舉例

趨勢是列舉型別代替 private final String CHANG_LIANG="Value";

類1,設定列舉型別

EnumTest.java

package com.demo.enumtest;

public enum EnumTest {
	//可以以逗號間隔
	PARAMETER_TEST("China"),
	PARAMETER_TEST2("China");
	
	private String a;
	private EnumTest(String a){
		this.a=a;
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return String.valueOf (this.a);
	}
        public String getA() {
		return a;
	}

	public void setA(String a) {
		this.a = a;
	}
}

類2,測試類呼叫列舉型別的常量

EnumGetParemater.java

package com.demo.enumtest;

import org.junit.Test;

public class EnumGetParemater {
	@Test
	public void testEnum(){
		System.out.println(EnumTest.valueOf("PARAMETER_TEST"));
		System.out.println(EnumTest.valueOf("PARAMETER_TEST").getA());
	}

}


測試結果:

China
China