java使用枚举类型

public enum Gender {

	MALE("男性", 1),
	FEMALE("女性", 0);
	
	// 性别名称
	private String name;
	
	// 性别值
	private int value;
	
	private Gender(String name, int value){
		this.name = name;
		this.value = value;
	}
	
	/**
	 * 获取性别名称
	 */
	public String getName(){
		return this.name;
	}
	
	/**
	 * 获取性别值
	 */
	public int getValue(){
		return this.value;
	}
	
	/**
	 * 根据值获取枚举
	 */
	public static Gender getGender(int value){
		if(MALE.getValue() == value){
			return MALE;
		} else if(FEMALE.getValue() == value){
			return FEMALE;
		} else {
			throw new RuntimeException("error");
		}
	}
}

   使用

public static void main(String[] args) {
		System.out.println(Gender.MALE.getName());
		System.out.println(Gender.MALE.getValue());
		
		Gender gender = Gender.getGender(1);
	}

猜你喜欢

转载自ln-software.iteye.com/blog/2357000