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)

好的,这也是有道理的,尽管自动完成工具提示没有(它声明 getDependencies 应该有 (null t) 作为它的参数)。我真的不知道从这里去哪里。我不能在 foreach 中使用通配符。我怎样才能满足我的 StructureUsingObject 可以接受具有 BaseRequest 子类的结构的要求,同时还能够使用列表中的元素调用 getDependencies?

4

1 回答 1

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
    }
}
于 2013-04-12T14:59:39.010 回答