枚举规范化

不使用Null Object

public static void main(String[] args) {
    // 根据code获取枚举对象
    ProductType productType = ProductType.getEnum(100);
    // 判断枚举对象是否获取成功、判断枚举对象是否为null
    System.out.println(productType == null); // true
    // 根据code获取message
    System.out.println(Optional.ofNullable(ProductType.getEnum(1)).map(ProductType::getMessage).orElse(null));// A产品
    System.out.println(Optional.ofNullable(ProductType.getEnum(200)).map(ProductType::getMessage).orElse(null));// null
}

@Getter
@AllArgsConstructor
public enum ProductType {

    /**
     * A产品类型
     */
    A_PRODUCT(1, "A产品"),

    /**
        * B产品类型
        */
    B_PRODUCT(2, "B产品"),
    ;

    /**
        * 产品类型代码
        */
    private final Integer code;

    /**
        * 产品类型描述
        */
    private final String message;

    /**
     * 根据产品类型代码获取产品类型
     *
     * @param code 产品类型代码
     * @return 产品类型
     */
    public static ProductType getEnum(Integer code) {
        return Arrays.stream(ProductType.values())
                .filter(e -> Objects.equals(e.getCode(), code))
                .findFirst()
                .orElse(null);
    }
}

使用Null Object

public static void main(String[] args) {
    // 根据code获取枚举对象
    ProductType productType = ProductType.getEnum(100);
    // 判断枚举对象是否获取成功、判断枚举对象是否为null
    System.out.println(productType.isNull()); // true
    // 根据code获取message
    System.out.println(ProductType.getEnum(1).getMessage()); // A产品
    System.out.println(ProductType.getEnum(200).getMessage()); // null
}

public interface DefaultNullable {

    default boolean isNull() {
        return false;
    }

}

@Getter
@AllArgsConstructor
public enum ProductType implements DefaultNullable {
    /**
     * 空产品类型
     */
    NULL_PRODUCT(null, null) {
        @Override
        public boolean isNull() {
            return true;
        }
    },

    /**
     * A产品类型
     */
    A_PRODUCT(1, "A产品"),

    /**
     * B产品类型
     */
    B_PRODUCT(2, "B产品"),
    ;

    /**
     * 产品类型代码
     */
    private final Integer code;

    /**
     * 产品类型描述
     */
    private final String message;

    /**
     * 根据产品类型代码获取产品类型
     *
     * @param code 产品类型代码
     * @return 产品类型
     */
    public static ProductType getEnum(Integer code) {
        return Arrays.stream(ProductType.values())
                .filter(e -> Objects.equals(e.getCode(), code))
                .findFirst()
                .orElse(NULL_PRODUCT);
    }
}

最后更新于