美文网首页
java.util.EnumSet.allOf()方法使用实例

java.util.EnumSet.allOf()方法使用实例

作者: wyn_做自己 | 来源:发表于2021-05-19 14:38 被阅读0次

今日份鸡汤:一点点积累,一步步成长。
好了,进入正题:

EnumSet类allOf()方法
allOf()方法在java.util包中可用。
allOf()方法用于返回具有给定元素类型(ele_ty)的所有元素的Enumset。
allOf()方法是一个静态方法,因此可以使用类名进行访问,如果尝试使用类对象访问该方法,则不会收到错误。

返回EnumSet对象时,allOf()方法可能会引发异常。
NullPointerException:当给定参数为null时,可能引发此异常。

语法:
public static EnumSet allOf(Class ele_ty);
参数:
ele_ty类–表示此Enumset的元素类型(ele_ty)类。
返回值:
此方法的返回类型为EnumSet,它检索具有此Enum元素集的Enumset。

来看一个实例吧:
实现类:

import lombok.Getter;
import org.springframework.util.StringUtils;

import java.util.EnumSet;
import java.util.Optional;

/**
 * java.util.EnumSet.allOf()方法使用实例
 */
@Getter
public enum ProductType {
    
    Food(1, "Foodstuff", "Food"),
    Drink(2, "Beverage", "Drink"),
    Clothes(3, "Accessories", "Clothes");

    private Integer value;
    private String oldName;
    private String newName;


    ProductType(Integer value, String oldName, String newName) {
        this.value = value;
        this.oldName = oldName;
        this.newName = newName;
    }

    /**
     * 通过历史定义的名称来获取商品类型
     * @param oldName
     * @return
     */
    private static ProductType getFromOldName(String oldName) {
        return EnumSet.allOf(ProductType.class)
                .stream()
                .filter(type -> !StringUtils.isEmpty(oldName) && oldName.equals(type.getOldName()))
                .findFirst()
                .orElse(null);
    }

    /**
     * 通过新定义的名称来获取商品类型
     * @param newName
     * @return
     */
    private static ProductType getFromNewName(String newName) {
        return EnumSet.allOf(ProductType.class)
                .stream()
                .filter(type -> !StringUtils.isEmpty(newName) && newName.equals(type.getNewName()))
                .findFirst()
                .orElse(null);
    }

    /**
     * 通过名称(兼容新老版本的名称)来获取商品类型
     * @param name
     * @return
     */
    public static ProductType getFromName(String name) {
        return Optional.ofNullable(getFromOldName(name)).orElse(getFromNewName(name));
    }

}

测试类:

/**
 * 这是一个测试类哦
 */
public class EnumSetDemo {
    public static void main(String[] args) {
        String productTypeName = "Beverage1";
//        String productTypeName = "Beverage";
        ProductType productType = ProductType.getFromName(productTypeName);
        if (productType == null) {
            System.out.println("不存在该商品类型,请重新填写~");
        }
        else {
            System.out.println("您选择的商品类型为:"+productType.getValue());
        }
    }
}

就到这吧~

相关文章

网友评论

      本文标题:java.util.EnumSet.allOf()方法使用实例

      本文链接:https://www.haomeiwen.com/subject/yaspjltx.html