다음 두 코드 샘플은 동일한 논리를 나타냅니다. 문자열이 null인지 확인하고 해당 검사를 기반으로 분기하는지 확인합니다. 첫 번째 샘플은 안전하게 컴파일됩니다. 두 번째는 Java 제네릭과 관련된 형식 불일치 오류를 생성합니다. 내 질문은 충분히 단순 해 보이지만 그것은 나를 벗어난다. 왜 컴파일러는이 두 문장을 다르게 취급합니까? 여기서 일어나는 일을 어떻게 더 잘 이해할 수 있습니까?이 두 조건은 컴파일러에서 다르게 취급되는 이유는 무엇입니까?
/* compiles cleanly */
protected Collection<String> getUserRoles(Object context,
Set<String> mappableRoles) {
String cookieValue = extractCookieValue(context);
if (cookieValue != null) {
return securityService.getRolesForUser(cookieValue);
} else {
return Collections.emptySet();
}
}
/* produces a compiler error */
protected Collection<String> getUserRoles(Object context,
Set<String> mappableRoles) {
String cookieValue = extractCookieValue(context);
return cookieValue == null ? Collections.emptySet()
: securityService.getRolesForUser(cookieValue);
}
Eclipse에서 컴파일러 오류가 발생했습니다. 요청한 바와 같이
Type mismatch: cannot convert from Set<capture#1-of ? extends Object> to Collection<String>
, 여기 SecurityService 인터페이스의 중요한 부분이다. Collections.emptySet()
이 지정되지 않은 Set
을 반환하기 때문에
public interface SecurityService {
public Set<String> getRolesForUser(String userId);
}
securityService.getRolesForUser()의 서명을 게시 할 수 있습니까? –
추가됨. 인터페이스에는 메소드가 하나 더 있지만이 예제에서는 호출되지 않습니다. –