列舉型別Enum用來存放系統常量
阿新 • • 發佈:2019-01-22
enum存放常量例項程式碼
1、寫介面,列舉型別的例子
public interface EnumValue<V> {
/**
* Returns this enum wrapper object value.
*/
public V getValue();
}
改進版
public interface EnumValue<K,V> {
/**
* @return 返回這個列舉物件的值
*/
public K getValue();
/**
* @return 返回這個值的描述
*/
public V getMsg();
}
2、寫Enum型別的
/**
* @since 2.0
*/
//這裡說明一下,還可以加一些私有變數,放在建構函式裡面
public enum ConstantsUtils implements EnumValue<String> {
PHP_SUCCESS(1, "返回成功"), PHP_ERROR(-1, "返回失敗"),
CHECKPARA_SUC(1, "檢驗成功"), ;
final int code;
final String name;
public int getCode () {
return code;
}
public String getName() {
return name;
}
private ConstantsUtils(int code, String name) {
this.code = code;
this.name = name;
}
@Override
public String getValue() {
return code + "";
}
}
3、使用如下程式碼
public class TestEnum {
public static void main(String[] args) {
if (ConstantsUtils.PHP_SUCCESS.getCode()!=1) {
System.out.println("你好陌生人");
}elseif(ConstantsUtils.PHP_SUCCESS.getValue()==1){
System.out.println("顯然這句話會被打印出來");
}
else{
System.out.println("顯然不成立");
}
}
}