java - 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,但目前每个值都是错误的
解决方案
解决您的用例的一种常见方法是:
- 将值存储在私有字段中(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));
推荐阅读
- r - 如何在 dplyr 的过滤器中正确使用 all?
- r - 错误 data.frame:未定义的列选择,闪亮的 R,lapply()
- arrays - 使用 mongodb 获得条件总和
- python - decorator on slot (PyQt)
- git - 在 android studio 中签出 Gitlab 的私有项目时身份验证失败
- c++ - 是否允许用不同的类型替换 `this`?
- email - php中邮件配置错误
- sql - 根据两列的组合选择count Distinct
- javascript - 如何在 Node.js 中找到我的浏览器的操作系统、架构类型等详细信息?
- ios - 应用因应用内购买而被拒绝