携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第4天,点击查看活动详情
前言:
枚举是Java1.5引入的新特性,通过关键字enum来定义枚举类。我们在工作中会经常使用枚举类,但是我最近发现有些工作了一两年的同学对枚举了解得还是比较少,只是在使用的层次,对枚举常用的方法也不怎么熟悉,下面我会详细介绍一下枚举的使用及常见方法和使用场景。
一丶枚举是什么?
枚举的本质其实就是一个类,一个隐式继承Enum类的类
- 特点:
- 枚举隐式继承Enum类,所以枚举无法再继承其他类,因为java是单继承
- 枚举不提供setXXX方法,因为枚举对象值通常为只读
- 枚举构造器私有,无法new出枚举对象
- 枚举对象/属性使用 static+final 共同修饰
下面看一个枚举类型
public enum ResultType {
SUCCESS_MESSAGE(1, "success message"),
FAIL_MESSAGE(2, "fail message"),
;
final int code;
final String message;
ResultType(int code, String message) {
this.code = code;
this.message = message;
}
public ResultType valueOf(int code) {
for (ResultType item : ResultType.values()) {
if (Objects.equals(code, item.getCode())) {
return item;
}
}
throw new NullPointerException("ResultType type not matched");
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
}
我们在项目中使用枚举一般会定义一个valueOf方法,根据code获取枚举对象的方法,这样我们想要通过code拿到我们枚举的其他属性就可以通过这个方法来拿到
二丶枚举自带的常用方法
我们这些常用的方法在我们的Enum类中都可以看到
name():我们可以直接拿到枚举的名称,就是我们写的常量值,比如上面示例代码的SUCCESS_MESSAGE,FAIL_MESSAGEvalues():这个方法在我们这个API中找不到,这个方法的作用是将枚举类型中的所有常量返回在枚举数组中,然后可以拿到这这个数组用于遍历所有的枚举值。
public static void main(String[] args) {
for (ResultType value : ResultType.values()) {
System.out.println(value);
}
}
输出结果:
SUCCESS_MESSAGE
FAIL_MESSAGE
valueOf(Stirng str):可以把一个字符串转换为对应的枚举类对象。参数name就是我们枚举的name。
public static void main(String[] args) {
ResultType successMessage = ResultType.valueOf("SUCCESS_MESSAGE");
System.out.println(successMessage.code); // 1
}
但是我们一般会在枚举类中写一个根据某个值获取Enum的方法
toString():默认的方法返回的是我们的Name,我们可以通过重写这个方法来使得我们的toString更易读。
System.out.println(ResultType.SUCCESS_MESSAGE.toString()); // SUCCESS_MESSAGE
clone():Enum的子类不能被克隆,调用clone()方法会抛出一个CloneNotSupportedException异常
protected final Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
ordinal():返回当前枚举常量的次序
System.out.println(ResultType.SUCCESS_MESSAGE.ordinal()); // 0
System.out.println(ResultType.FAIL_MESSAGE.ordinal()); // 1
总结
枚举的基本使用其实很简单,下一章我会介绍一下枚举的进阶使用,及枚举的一些使用场景,下一章干货满满,请勿错过!!!