[英]Calling java method with Set with nested “?” generic type
我在可重用的類中有這樣的方法:
public String buildMessageForViolation(ConstraintViolation<?> constraintViolation) {
return constraintViolation.getPropertyPath().toString().replace(".<collection element>", "") + ": " + constraintViolation.getMessage();
}
它是從另一個類調用的:
fieldValidator.appendErrorMessage(getUslValidator().buildMessageWithProperty(constraintViolations.iterator().next()) +
(constraintViolations.size() > 1 ? ", and other errors" : ""));
所以,因為我希望在許多類中重復這個塊,所以我想重構它,因此復雜性在可重用的類中,而不是在客戶端代碼中。
所以,我然后將其添加到可重用的類中:
public String buildMessageForViolations(Set<ConstraintViolation<?>> constraintViolations) {
return buildMessageForViolation(constraintViolations.iterator().next()) +
(constraintViolations.size() > 1 ? ", and other errors" : "");
}
然后將客戶端代碼更改為:
fieldValidator.appendErrorMessage(getUslValidator().buildMessageForViolations(constraintViolations));
這不編譯,說:
The method buildMessageForViolations(Set<ConstraintViolation<?>>) in the type USLValidator is not applicable for the arguments (Set<ConstraintViolation<ClientSpecificClassName>>)
顯然,這與我指定“?”的事實有關。 對於嵌套類型參數。 從我的角度來看,這是合適的,因為可重用的類不關心ConstraintViolation的類型參數。
我能解決這個問題嗎?
更新 :
我正在閱讀發布到此的答案,以及隨后對答案的編輯,但隨后由於某種原因被刪除(猜測響應者放棄了嘗試使其正確)。
雖然答案仍然存在,但它至少幫助我找到了一個合理的解決方法。
客戶端代碼可以改為:
fieldValidator.appendErrorMessage(getUslValidator().buildMessageForViolations(new HashSet<ConstraintViolation<?>>(constraintViolations)));
這至少比原版好一點,盡管還有一些人們必須記住的樣板。
嵌套通配符可能會導致一些意外的不兼容性。 嘗試這個:
public String buildMessageForViolations(Set<? extends ConstraintViolation<?>> constraintViolations) {
我會把方法寫成:
public String buildMessageForViolations(Set<ConstraintViolation> constraintViolations) {..}
這告訴編譯器它需要一組任何類型的ConstraintViolation
。 我認為在這種情況下,這是你試圖告訴編譯器的內容。
使用客戶端代碼:
ConstraintViolation cv = new StringConstraintViolation();
USLValidator uslValidator = new USLValidator();
Set<ConstraintViolation> constraintViolationSet = new HashSet<>();
constraintViolationSet.add(cv);
uslValidator.buildMessageForViolations(constraintViolationSet);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.