枚举的定义
public enum TestEnum {
A1(1, "lisa"),
A2(2, "jak");//定义枚举类对象,它是通过构造方法来创建的,所以得重载构造方法
private Integer key;
private String value;//定义枚举类中的成员变量
/**
*
* @param key
* @param value
*/
TestEnum(Integer key, String value) {
this.key = key;
this.value = value;
}
/**
* 自定义一个通过key获取value的方法
* @param key
* @return
*/
public String getValueByKey(Integer key) {
TestEnum[] values = values();
for (TestEnum name : values) {
if (name.getKey() == key) {
return name.getValue();
}
}
return "name not exist";
}
public Integer getKey() {
return key;
}
public void setKey(Integer key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Test
public static void main(String[] args) {
new TestG().enumTest(1);
}
private void enumTest(Integer key){
System.out.println(TestEnum.A1.getValueByKey(key));
}