限制从int到enum类的转换可以通过以下几种方式实现:
public enum MyEnum {
VALUE1,
VALUE2,
VALUE3;
public static MyEnum fromInt(int value) {
switch (value) {
case 1:
return VALUE1;
case 2:
return VALUE2;
case 3:
return VALUE3;
default:
throw new IllegalArgumentException("Invalid value: " + value);
}
}
}
public enum MyEnum {
VALUE1,
VALUE2,
VALUE3;
private static final Map<Integer, MyEnum> map = new HashMap<>();
static {
map.put(1, VALUE1);
map.put(2, VALUE2);
map.put(3, VALUE3);
}
public static MyEnum fromInt(int value) {
MyEnum result = map.get(value);
if (result == null) {
throw new IllegalArgumentException("Invalid value: " + value);
}
return result;
}
}
public enum MyEnum {
@IntValue(1)
VALUE1,
@IntValue(2)
VALUE2,
@IntValue(3)
VALUE3;
public static MyEnum fromInt(int value) {
for (MyEnum e : MyEnum.values()) {
IntValue annotation = e.getClass().getField(e.name()).getAnnotation(IntValue.class);
if (annotation != null && annotation.value() == value) {
return e;
}
}
throw new IllegalArgumentException("Invalid value: " + value);
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface IntValue {
int value();
}
以上是限制从int到enum类的转换的几种方法,根据具体的需求和场景选择合适的方法。腾讯云提供的相关产品和服务可以参考腾讯云官方文档:腾讯云产品与服务。
领取专属 10元无门槛券
手把手带您无忧上云