提问人:Jossany Moura 提问时间:10/31/2023 最后编辑:Jossany Moura 更新时间:11/8/2023 访问量:117
如何在java中进行枚举验证?
How to make an enum validation in java?
问:
这是一个 quarkus java 项目。
我试图验证的 bean 是:
import io.quarkus.runtime.annotations.RegisterForReflection;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.eclipse.microprofile.openapi.annotations.media.Schema;
import javax.validation.constraints.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@NoArgsConstructor
@AllArgsConstructor
@Data
@RegisterForReflection
public class Launche {
public static final int VALUE_100 = 100;
public static final int VALUE_40 = 40;
public static final int VALUE_10 = 10;
public static final int VALUE_6 = 6;
public static final int VALUE_2 = 2;
@NotNull
@Schema(description = "Transaction date", example = "2023-02-21T10:00:00.000Z")
private LocalDateTime date;
@NotBlank
@Size(max = VALUE_100, message = "size must be between 1 and 100")
@Schema(description = "Transaction description", example = "Marketplace")
private String description;
@NotNull
@PositiveOrZero
@Schema(format = "BigDecimal", description = "Transaction amount", example = "10.00")
@Digits(integer = VALUE_10, fraction = VALUE_2)
private BigDecimal amount;
**@NotNull
@Schema(format = "enum", description = "Launche type", example = "COMPRA")
private TypeLaunche type;**
@NotNull
@Schema(description = "Score", example = "true")
private Boolean score;
@Size(max = VALUE_40, message = "size must be between 1 and 40")
@Schema(description = "Transaction establishment name", example = "Marketplace")
private String establishmentName;
@NotNull
@Schema(format = "BigDecimal", description = "Real dollar quote of the day", example = "4.50")
@Digits(integer = VALUE_6, fraction = VALUE_6)
private BigDecimal dollarQuotation;
@Override
public String toString() {
return GsonFactory.getInstance().toJson(this);
}
}
枚举类为:
import lombok.AllArgsConstructor;
import lombok.Getter;
@AllArgsConstructor
@Getter
public enum TypeLaunche {
COMPRA("COMPRA"),
ESTORNO("ESTORNO"),
PAGAMENTO("PAGAMENTO"),
OUTROS("OUTROS");
private String value;
}
我的验证类是:
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class EnumTypeValidatorImpl implements ConstraintValidator<EnumTypeValidator, CharSequence> {
private List<String> acceptedValues;
@Override
public void initialize(final EnumTypeValidator annotation) {
acceptedValues = Stream.of(annotation.enumClass().getEnumConstants())
.map(Enum::name)
.collect(Collectors.toList());
}
@Override
public boolean isValid(final CharSequence value, final ConstraintValidatorContext context) {
if (value == null) {
return true;
}
return acceptedValues.contains(value.toString());
}
}
当我发送与枚举选项不同的类型时,我的解析器将其设置为 null。验证者不应该因为它与枚举选项不同而抛出错误吗?我在 Bean 中将类型设置为 TypeLaunche。
我想我不明白这种验证是如何工作的。
更新
我用于分析申请正文的代码。 更多详细信息:type 是 Launche 类的一个属性,Launche 是 CardInvoice 类的一个属性。CardInvoice 是我用来分析申请正文的类。代码如下:
private CardInvoice parseCardInvoiceFromMessageBody(final String body) {
LOGGER.info("Parsing API Gateway Message into CardInvoice object.");
Gson gson = GsonFactory.getInstance();
try {
var obj = gson.fromJson(body, CardInvoice.class);
LogUtil.setRequestUuid(obj.getUuid());
return obj;
} catch (Exception ex) {
LOGGER.error("Invalid API Gateway Message body.", ex);
String value = extractValueErrorMessage(String.valueOf(ex));
JsonElement jsonElement = JsonParser.parseString(body);
List<String> fields = null;
if (jsonElement.isJsonObject()) {
JsonObject jsonObject = jsonElement.getAsJsonObject();
fields = findKeys(jsonObject, value);
}
throw new InvalidMessageBodyException(String.format("Invalid API Gateway Message body. "
+ "Parse fields: [%s], value: [%s]", fields, value));
}
}
答:
0赞
Aloysius Tri Sulistyo Putranto
11/8/2023
#1
试试这个
public enum TypeLauncher {
COMPRA("COMPRA"),
ESTORNO("ESTORNO"),
PAGAMENTO("PAGAMENTO"),
OUTROS("OUTROS");
private final String name;
TypeLaunche(String name) {this.name = name;}
public String getName() {return name;}
}
并设置列表
List<String> acceptedValues = Stream.of(TypeLauncher.values()).map(TypeLauncher::getName).collect(Collectors.toList());
比你可以比较它
评论