- 说明
- 分享
- 介绍
- 枚举方法
- 枚举判断
- 实例
- 简单枚举
- 复合枚举
- 总结
分享本博客每周五更新一次。
枚举是日常java开发中重要的数据处理类型,常用作公共状态值管理,以名称方式使用状态值代码直观,集中化的管理方式方便修改和调整。
- 大数据博客列表
- 开发记录汇总
- 个人java工具库 项目https://gitee.com/wangzonghui/object-tool
- 包含json、string、集合、excel、zip压缩、pdf、bytes、http等多种工具,欢迎使用。
| 名称 | 说明 |
|---|---|
| values() | 返回 enum 实例的数组,而且该数组中的元素严格保持在 enum 中声明时的顺序。 |
| name() | 返回实例名。 |
| ordinal() | 返回实例声明时的次序,从0开始。 |
| getDeclaringClass() | 返回实例所属的 enum 类型。 |
| equals() | 判断是否为同一个对象。可以使用 == 来比较enum实例。 |
- 使用switch判断枚举类型,完成对应操作。
XmlType xmltype=XmlType.ACTION
log.info("Deal Type:{} ",xmltype.name());
switch(xmltype) {
case ACTION:
break;
case RESULT:
break;
default:
break;
}
实例
简单枚举
public enum XmlType {
ACTION(0),FORK(1),JOIN(2),RESULT(3);
private final int code ;
XmlType(int code) {
this.code=code;
}
public int getCode() {
return code;
}
public static XmlType fromType(int vale) {
return EnumSet.allOf(XmlType.class).stream().filter(s -> s.getCode()==value).findAny().orElseThrow(() -> new IllegalArgumentException("Invalid status: " + value));
}
}
复合枚举
- 枚举中包含枚举。
package com.think.cn.properties;
public enum TypeEnum {
sourcePath("source.path",Type.pathString.typeValue),outputPath("output.path",Type.pathString.typeValue);
private String name;
private int type;
TypeEnum() {}
TypeEnum(String name,int type){
this.name=name;
this.type=type;
}
public String getName() {
return this.name;
}
public int getType() {
return this.type;
}
enum Type{
stringValue(0),intValue(1),longValue(2),pathString(3);
private int typeValue;
Type(int type){
this.typeValue=type;
}
public int getValue() {
return this.typeValue;
}
}
}
总结
- 枚举属性为static final修饰,引用不必new,且不可变。



