java switch和枚举类的结合

switch 语句中的变量类型可以是: byte、short、int 或者 char。从 Java SE 7 开始,switch 支持字符串 String 类型了,同时 case 标签必须为字符串常量或字面量。
我们创建一个枚举:

@Getter
@AllArgsConstructor
public enum ProductEnum {

	TYPE_1(1,"精品推荐"),
	TYPE_2(2,"热门榜单"),
	TYPE_3(3,"首发新品"),
	TYPE_4(4,"猜你喜欢");


	private Integer value;
	private String desc;
}

用switch语句:

 int a = 0;
        // order
        switch (a) {
            //精品推荐
            case ProductEnum.TYPE_1.getValue():
                System.out.println("1");
                break;
            //首发新品
            case ProductEnum.TYPE_2.getValue():
                System.out.println("1");
                break;
            // 猜你喜欢
            case ProductEnum.TYPE_3.getValue():
                System.out.println("1");
                break;
            // 热门榜单
            case ProductEnum.TYPE_4.getValue():
                System.out.println("1");
                break;
        }

看上去没有问题,但是因为switch中需要的是一个常量,但是枚举中又是不可以加final关键字,所以会出现这种情况:(Constant expression required:需要常量表达式
在这里插入图片描述

我们想要使用就需要封装一个方法在枚举类里面:

	public static ProductEnum toType(int value) {
		return Stream.of(ProductEnum.values())
				.filter(p -> p.value == value)
				.findAny()
				.orElse(null);
	}

封装后的枚举类:

@Getter
@AllArgsConstructor
public enum ProductEnum {

	TYPE_1(1,"精品推荐"),
	TYPE_2(2,"热门榜单"),
	TYPE_3(3,"首发新品"),
	TYPE_4(4,"猜你喜欢");


	private Integer value;
	private String desc;

	public static ProductEnum toType(int value) {
		return Stream.of(ProductEnum.values())
				.filter(p -> p.value == value)
				.findAny()
				.orElse(null);
	}


}

这个时候我们这么用:

   int a = 0;
        switch (ProductEnum.toType(a)) {
            //精品推荐
            case TYPE_1:
                System.out.println("1");
                break;
            //首发新品
            case TYPE_3:
                System.out.println("2");;
                break;
            // 猜你喜欢
            case TYPE_4:
                System.out.println("3");
                break;
            // 热门榜单
            case TYPE_2:
                System.out.println("4");
                break;
        }

这样就没问题啦:
在这里插入图片描述

posted @ 2021-03-04 15:19  MrFugui  阅读(453)  评论(0编辑  收藏  举报