错误:

Type mismatch: cannot convert from Set<ConstraintViolation<capture#1-of ?>> to Set<ConstraintViolation<Class<?>>>
.

我的代码:

public class validateValue(Class<?> beanType, String propertyName, Object value, Class<?>... groups){
    TraversableResolver tr = new MyTraversableResolver(); 
    Validator validator = Validation.buildDefaultValidatorFactory().usingContext().traversableResolver(tr).getValidator();
    final Set<ConstraintViolation<Class<?>>> constraintViolations = validator.validateValue(beanType, propertyName, value, groups);
}

private class MyTraversableResolver  implements TraversableResolver {

    public boolean isReachable(Object traversableObject, Path.Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) {
      return traversableObject == null || Hibernate.isInitialized(traversableObject);
      }
      public boolean isCascadable(Object traversableObject, Path.Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) {
          return true;
      }
  }
.

有帮助吗?

解决方案

@JustinKSU is correct about changing the wildcard (?) to a type arg (T). The other issue is that validator.validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups) doesn't return a set of constraint violations on the type's class, which would be:

Set<ConstraintViolation<Class<T>>>

...but rather it returns a set of constraint violations on the type:

Set<ConstraintViolation<T>>

It's a subtle difference to see, but it's noticeable if you check the error message closely and count the angle brackets.

So, your code should be as below. I simplified the validator creation for purposes of the example. I also added a return value since I assume you want to do something with the results.

public <T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups) {
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    final Set<ConstraintViolation<T>> constraintViolations = validator.validateValue(beanType, propertyName, value, groups);
    return constraintViolations;
}

其他提示

I think the problem is your compiler doesn't know that the type of your beanType variable matches the set. Try something like this (code may need to be tweaked a bit)

public <T> class validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups)

Then changing:

 final Set<ConstraintViolation<Class<?>>>

to

 final Set<ConstraintViolation<Class<T>>>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top