首页 > 解决方案 > Java字符串/整数不会解析为枚举

问题描述

我在java中有以下枚举

public enum TypeSignsEnum {

    NEGATIVE("45","17","11","66","31","56","85","14","15","91","30"),
    POSITIVE("58","26","97","12","89","18","22","19","20","16","25","92","10","14","24","60","65","79","57","27","23","96"),
    DEFAULT();

    TypeSignsEnum(String ...values) {
        List<String> values1 = Arrays.asList(values);
    }

}

每个都有多个输入值(也是默认值,但还没有),以下所有逻辑都取决于此..

但是,这总是会导致错误

java.lang.NullPointerException: Name is null

或者如果我尝试使用实际Integers

No enum constant com.xxx.zzz.yyy.model.TypeSignsEnum.11

( 11 是左数第三个,负数...)

相同的代码,但有Integers

public enum TypeSignsEnum {

    NEGATIVE(45, 17, 11, 66, 31, 56, 85, 14, 15, 91, 30),
    POSITIVE(58, 26, 97, 12, 89, 18, 22, 19, 20, 16, 25, 92, 10, 14, 24, 60, 65, 79, 57, 27, 23, 96),
    DEFAULT();

    TransactionTypeSignsEnum(Integer ...values) {
        List<Integer> values1 = Arrays.asList(values);
    }

}

我如何使这项工作?

关键是其他类调用valueOf(value)应该是 NEGATIVE 或 POSITIVE,但目前每个值都是错误的

标签: javaenumsconstructor

解决方案


解决您的用例的一种常见方法是:

  • 将值存储在私有字段中(Java 中的枚举不是简单的常量,它们可以有字段和方法)
  • 添加一个公共静态方法来搜索您的枚举值
public enum TypeSignsEnum {

    NEGATIVE(45, 17, 11, 66, 31, 56, 85, 14, 15, 91, 30),
    POSITIVE(58, 26, 97, 12, 89, 18, 22, 19, 20, 16, 25, 92, 10, 14, 24, 60, 65, 79, 57, 27, 23, 96),
    DEFAULT();

    private final HashSet<Integer> values;

    TypeSignsEnum(Integer ...values) {
        this.values = new HashSet<>(Arrays.asList(values));
    }

    public static TypeSignsEnum fromValue(int value) {
        for (TypeSignsEnum e : TypeSignsEnum.values()) {
            if (e.values.contains(value)) {
                return e;
            }
        }
        return DEFAULT;
    }

}

用法:

System.out.println(TypeSignsEnum.fromValue(11));

推荐阅读