java 枚举

java 枚举,第1张

文章目录
  • 说明
  • 分享
  • 介绍
    • 枚举方法
    • 枚举判断
  • 实例
    • 简单枚举
    • 复合枚举
  • 总结

说明

本博客每周五更新一次。
枚举是日常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() {}
	
	/**
	 * 构造方法
	 * @param name 属性名
	 * @param type 属性类型 0 字符串 1 int  2 long 3 路径
	 */
	TypeEnum(String name,int type){
		this.name=name;
		this.type=type;
	}
	
	/**
	 * 获取属性名
	 * @return
	 */
	public String getName() {
		return this.name;
	}
	
	/**
	 * 获取类型名
	 * @return
	 */
	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,且不可变。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/877885.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-13
下一篇2022-05-13

发表评论

登录后才能评论

评论列表(0条)

    保存