2011-05-16 82 views
0

錯誤:爲什麼我的編譯器無法將其轉換?

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

回答

0

@JustinKSU是有關更改通配符正確的(?)到一個類型arg(T)。另一個問題是,validator.validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups)不會對類型的類返回一組約束違規的,這將是:

Set<ConstraintViolation<Class<T>>> 

...而是返回該類型的一組約束違規:

Set<ConstraintViolation<T>> 

這看起來有點不同,但如果仔細檢查錯誤消息並計算尖括號,則會引人注目。

所以,你的代碼應該如下。出於示例的目的,我簡化了驗證器創建。我還添加了一個返回值,因爲我假設你想對結果做些什麼。

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; 
} 
1

我認爲這個問題是你的編譯器不知道你beanType變量的類型設定相匹配。嘗試這樣的事情(代碼可能需要進行調整了一下)

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

然後改變:

final Set<ConstraintViolation<Class<?>>> 

final Set<ConstraintViolation<Class<T>>> 
+0

如果這樣不起作用,請嘗試用替換「類」 – JustinKSU 2011-05-16 23:30:14

相關問題