Domanda

I am working with javax.validation / Hibernate validation. To validate an annotated (e.g. @NotNull at an attribute) bean, the hibernate validator is used with the javax.validation interfaces:

Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

public interface Validator {
    <T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups);
}

public interface ConstraintViolation<T> {
    String getMessage();
    Path getPropertyPath(); 
    T getRootBean();
}

The goal is to write a single method, which accepts differently typed sets, like:

Set<ConstraintViolation<TaskList>> violationsTaskList = validator.validate(taskList);
Set<ConstraintViolation<TaskItem>> violationsTaskItem = validator.validate(taskItem);

public void consumeViolations(Set<ConstraintViolation<?> violations) {
    // Do something meaningful...
    violations.getMessage();
}

Using the wildcard ? is best think I came up with until now but it is rejected by the compiler with the message:

consumeViolations(....<?>) cannot be applied to consumeViolations(....<TaskList>)

I do not want to write this method for every type T just to call getMessage() and pass it to the next method.

Is it possible to write such a method? I only want to access methods of the ConstraintViolation interface, which are not dependent on the type T like String getMessage().

È stato utile?

Soluzione

I think what you need is

public void consumeViolations(Set<? extends ConstraintViolation<?>> violations) {}

or like

public <T, V extends ConstraintViolation<T>> void consumeViolations(Set<V> violations) {}

depending on what you need to do with the Set inside the method.

This is just regular behavior of generics which are not normally covariant. You may know that a List<Dog> is not a List<Animal> and the same thing applies here.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top