开发者

Why can't my compiler convert this?

Error:

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

My code:

public class validateValue(Class<?> beanType, String propertyName, Object v开发者_运维技巧alue, 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;
      }
  }


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>>>


@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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜