栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java Enum类(常用方法详解和演示)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java Enum类(常用方法详解和演示)

方便日后回顾

public class EnumTestDemo02 {
    public static void main(String[] args) {
        
        switch (Season.valueOf("SUMMER")) {
            case SPRING:
                System.out.println("春天");
                break;
            case SUMMER:
                System.out.println("夏天");
                break;
            case AUTUMN:
                System.out.println("秋天");
                break;
            case WINTER:
                System.out.println("冬天");
                break;
            default:
                System.out.println("没有季节的一天~~~");
        }
        System.out.println(Season.AUTUMN);//AUTUMN("不是字符串类型")
        System.out.println(Season.valueOf("AUTUMN"));//AUTUMN("不是字符串类型")
        System.out.println(Season.AUTUMN.name());//AUTUMN("字符串类型")
        //补充:2种方式判断是否是字符串类型
        //1.instanceof
        System.out.println(Season.AUTUMN instanceof Season);//true,说明是枚举类型
        System.out.println(Season.valueOf("AUTUMN") instanceof Season);//true,说明是枚举类型
        System.out.println(Season.AUTUMN.name() instanceof String);//true,说明是字符串类型
        //2.反射方式
        try {
			//这里只是判断枚举类中的AUTUMN枚举的类型
           System.out.println(Season.class.getDeclaredField("AUTUMN").getType());//class Season
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        System.out.println(Season.AUTUMN.name());//AUTUMN
        System.out.println(Season.AUTUMN.description());//秋天
        System.out.println(Season.AUTUMN.month());//789
        Season winter = Season.WINTER;
        System.out.println(winter);//WINTER

        Season[] values = Season.values();
        for (int i = 0; i < values.length; i++) {
            
            System.out.println(values[i]);
        }

        //遍历循环
        for (Season season : Season.values()) {
            
            System.out.println("season: "+season);
            System.out.println("season.name():"+season.name()+" 下标: "+ season.ordinal());
        }
    }
}

Season 枚举类

public enum Season {
    
    SPRING("春天",123),
    SUMMER("夏天",456),
    AUTUMN("秋天",789),
    WINTER("冬天",101112);
    private final String description;
    private Integer month;
    Season(String description, Integer month) {
        this.description = description;
        this.month = month;
    }

    public Integer month(){
        return month;
    }

    public String description(){
        return description;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/462038.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号