gpt4 book ai didi

java - 使用带有嵌套 "?"泛型类型的 Set 调用 java 方法

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

我在可重用类中有这样的方法:

public String buildMessageForViolation(ConstraintViolation<?> constraintViolation) {
return constraintViolation.getPropertyPath().toString().replace(".<collection element>", "") + ": " + constraintViolation.getMessage();
}

它是从另一个类调用的,如下所示:

 fieldValidator.appendErrorMessage(getUslValidator().buildMessageWithProperty(constraintViolations.iterator().next()) +
(constraintViolations.size() > 1 ? ", and other errors" : ""));

因此,由于我希望这个 block 在许多类中重复,所以我想重构它,以便复杂性位于可重用类中,而不是客户端代码中。

因此,我将其添加到可重用类中:

public String buildMessageForViolations(Set<ConstraintViolation<?>> constraintViolations) {
return buildMessageForViolation(constraintViolations.iterator().next()) +
(constraintViolations.size() > 1 ? ", and other errors" : "");
}

然后将客户端代码更改为:

fieldValidator.appendErrorMessage(getUslValidator().buildMessageForViolations(constraintViolations));

这不会编译,说:

The method buildMessageForViolations(Set<ConstraintViolation<?>>) in the type USLValidator is not applicable for the arguments (Set<ConstraintViolation<ClientSpecificClassName>>)

显然这与我指定“?”有关。对于嵌套类型参数。从我的角度来看,这是合适的,因为可重用类不关心 ConstraintViolation 的类型参数。

我可以做一些简单的事情来解决这个问题吗?

更新:

我正在阅读发布于此的答案,以及对该答案的后续编辑,但后来由于某种原因被删除(猜测响应者放弃了尝试使其正确)。

虽然答案仍然存在,但它至少帮助我找到了一个合理的解决方法。

客户端代码可以这样做:

fieldValidator.appendErrorMessage(getUslValidator().buildMessageForViolations(new HashSet<ConstraintViolation<?>>(constraintViolations)));

这至少比原来的好一点,尽管仍然有一些人们必须记住的样板文件。

最佳答案

嵌套通配符可能会导致一些意外的不兼容性。试试这个:

public String buildMessageForViolations(Set<? extends ConstraintViolation<?>> constraintViolations) {

关于java - 使用带有嵌套 "?"泛型类型的 Set 调用 java 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44707674/

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