gpt4 book ai didi

java - 可选,@NotBlank 给出错误,而 @Size 不给出使用 Javax 验证的不可变类

转载 作者:太空宇宙 更新时间:2023-11-04 09:23:14 26 4
gpt4 key购买 nike

我有以下 POJO:

import java.util.Optional;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

import org.immutables.value.Value;

@Value.Immutable
public interface ABC {
Optional<@NotBlank String> test();

Optional<@Size(max = 280) String> testSize();
}

我正在使用 javax 验证来验证 ABC 类的对象,如下所示:

public static Set<TestConstraintViolation> validateInternalTest(final Object type, final Class<?>... groups) {
Set<TestConstraintViolation> violations = new HashSet<>();
for (Method method : type.getClass().getInterfaces()[0].getDeclaredMethods()) {
try {
VALIDATOR.validateReturnValue(
type,
method,
method.invoke(type),
groups).forEach(constraint -> {
TestConstraintViolation testConstraintViolation = new TestConstraintViolation(
method.getName(),
constraint.getMessageTemplate()
);
violations.add(testConstraintViolation);
});
} catch (IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException("", e);
}
}
return violations;
}

现在,当我尝试使用 ABC 的 validator 函数对象进行验证时,我看到一个奇怪的问题:

@Test
public void test() {
ABC abc = ABCType.builder().build();
assertThat(validateInternalTest(abc))
.hasViolation("test", "{javax.validation.constraints.NotBlank.message}");

ABC abc2 = ABCType.builder().test("test").build();
assertThat(validateInternalTest(abc2))
.hasNoViolations();
}

对于 abc 对象,如果测试未通过,它会返回违规,即使它是可选的,但未通过 testSize 工作正常。

据我所知,使用Optional,它们都应该可以工作。不是吗?

Immutables 或 javax 验证有问题吗?请帮忙。

最佳答案

What is the Optional type? Optional is a new container type that wraps a single value, if the value is available. So it's meant to convey the meaning that the value might be absent. Take for example this method:

如果您使用Optional,这意味着值可能不存在,并且将@NotBlank与Optional结合使用对我来说似乎不是一个明智的主意。

关于java - 可选,@NotBlank 给出错误,而 @Size 不给出使用 Javax 验证的不可变类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58055802/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com