繁体   English   中英

Java通用通配符运算符

[英]Java generics wildcard operator

我正在尝试编写一种实用程序方法,以协助我针对应用程序中与bean验证有关的任何验证错误构建异常消息。 当我验证我的对象(在本例中为BasicContactInformation)时,我按以下步骤进行操作:

Set<ConstraintViolation<BasicContactInformation>> constraintViolations = validator.validate(basicContactInformation);
        if(!CollectionUtils.isEmpty(constraintViolations)){
            throw new CustomerAccountException(LoggingUtils.getLoggingOutput("Unable to update customer contact information", constraintViolations));
        }

我对其他豆类也做同样的事情。 实用程序方法将为异常消息加上前缀约束约束集合,并构建格式正确的输出消息。 问题是,我无法弄清楚如何构建消息以使其可以接受一组任何类型的约束违例。 我尝试了以下操作,但似乎无效,因为它说它不能投射:

public static String getLoggingOutput(String prefix, Set<ConstraintViolation<?>> violations){
    StringBuilder outputBuilder = new StringBuilder(prefix);
    if(!CollectionUtils.isEmpty(violations)){
        for(ConstraintViolation<?> currentViolation: violations){
            outputBuilder.append("[");
            outputBuilder.append(currentViolation.getMessage());
            outputBuilder.append("]");
        }
    }
    return outputBuilder.toString();
}

这是编译器错误

The method getLoggingOutput(String, Set<ConstraintViolation<?>>) in the type LoggingUtils is not applicable for the arguments (String, Set<ConstraintViolation<BasicContactInformation>>)

关于方法签名应该是什么的想法,以便它可以用于任何违反约束的集合? 我试图避免编写一种方法,该方法对foo,对bar,对baz等一组约束违反。

您可以使方法通用:

public static <T> String getLoggingOutput(String prefix,
        Set<ConstraintViolation<T>> violations) {
    // ...
}

在大多数情况下,即使不是全部,编译器也会从参数中推断出type参数。 这与使用通配符根本不一样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM