2015-01-21 30 views
0

我無法理解通配符捕獲錯誤,或找到一種方法來繞過它:通配符捕獲錯誤:爲什麼?

import java.util.List; 


class A<B extends A.AA<? extends C>, C> { 

    List<C> list; 

    public void foo(B inner) { 
    C c = get(); 
    inner.nop(c); 
    } 

    private C get() { 
    return list.get(0); 
    } 

    static public class AA<D> { 
    public void nop(D d) { 
     System.out.println(d); 
    } 
    } 
} 

這裏的javac的輸出中:

Wildcards.java:10: error: method nop in class AA<D> cannot be applied to given types;     
     inner.nop(c);                     
     ^                      
required: CAP#1                      
found: C                       
reason: actual argument C cannot be converted to CAP#1 by method invocation conversion    
where C,D are type-variables:                  
    C extends Object declared in class A                
    D extends Object declared in class AA                
where CAP#1 is a fresh type-variable:                
    CAP#1 extends C from capture of ? extends C              
1 error 

我們爲什麼不能傳給C的一個實例B.nop()?

回答

2

比方說,你創建的A一個實例:

A<A.AA<String>,Object> a = new A<A.AA<String>,Object>(); 
A.AA<String> inner = new A.AA<String>(); 
a.foo(inner); 

inner.nop()應該期待一個String,但你傳遞一個Object

一個可能的解決方法是:

class A<B extends A.AA<C>, C> 
+0

OP也許感興趣的重寫她的代碼的解決方案。 – Stephan 2015-01-21 10:44:08

相關問題