2013-04-12 53 views
0

我對包含使用泛型的成員的類有些麻煩。考慮下面的示例類:上限制泛型的問題

class BaseRequest { 
    // Content goes here 
} 

class SubRequest extends BaseRequest { 
    // IFace methods go here, etc. 
} 

// Simple datastructure interface 
interface Structure<T> { 

    List<T> getElementsList(); 


    Collection<T> getDependencies(T t); 
} 

// Simple structure implementation, details unimportant 
class StructureImpl<T> implements Structure<T> { 

    @Override 
    public List<T> getElementsList() { 
     // Implementation details not important 
     return null; 
    } 


    @Override 
    public Collection<T> getDependencies(T t) { 
     // implementation details not important 
     return null; 
    } 
} 

然後我有一個使用結構

class StructureUsingObject { 
    final Structure<BaseRequest> structure; 


    public StructureUsingObject(Structure<BaseRequest> structure) { 
     this.structure = structure; 
    } 


    public void foo() { 
     for (BaseRequest request : structure.getElementsList()) { 
      Collection<BaseRequest> requests = this.structure.getDependencies(request); 
      // do things 
     } 
    } 
} 

通過自身下面的類,這是不行的;

public void foo() { 
    StructureImpl<BaseRequest> baseImpl = new StructureImpl<BaseRequest>(); 
    StructureUsingObject baseStruct = new StructureUsingObject(baseImpl); 

    StructureImpl<SubRequest> subImpl = new StructureImpl<SubRequest>(); 
    // Compile error on this line 
    StructureUsingObject subStruct = new StructureUsingObject(subImpl); 
} 

這很有道理; StructureImpl <BaseRequest>未執行StructureImpl <SubRequest>的子類。因此,我嘗試修改StructureUsingObject以使用通配符:

class StructureUsingObject { 
    final Structure<? extends BaseRequest> structure; 


    public StructureUsingObject(Structure<? extends BaseRequest> structure) { 
     this.structure = structure; 
    } 


    public void foo() { 
     for (BaseRequest request : structure.getElementsList()) { 
      // Compile error on this line 
      Collection<BaseRequest> requests = this.structure.getDependencies(request); 

      // To clarify, a compile error would happen here as well; the issue isn't with the return type 
      this.structure.getDependencies(request); 

      // do things 
     } 
    } 
} 

這也行不通;

The method getDependencies(capture#4-of ? extends BaseRequest) in the type Structure<capture#4-of ? extends BaseRequest> is not applicable for the arguments (BaseRequest) 

OK,這是有道理的太多,雖然自動完成提示不(它指出getDependencies應該有(空T)作爲參數)。我不確定該從哪裏出發。我不能在foreach中使用通配符。我如何滿足這樣的要求,即我的StructureUsingObject可以接受具有BaseRequest子類的Structures,但同時也可以使用列表中的元素調用getDependencies?

回答

2

修改您的最新版本以捕獲通配符。

public void foo() { 
    bar(this.structure); 
} 

private <T extends BaseRequest> void bar(Structure<T> s) { 
    for (T request : s.getElementsList()) { 
     Collection<T> requests = s.getDependencies(request); 

     // do things 
    } 
} 
+0

謝謝,這正是我正在尋找的! – vol