简体   繁体   English

了解Java泛型 <T extends Class> 和 <? extends Class>

[英]Understanding Java Generics <T extends Class> and <? extends Class>

This may be a dumb question so please excuse my ignorance. 这可能是一个愚蠢的问题,所以请原谅我的无知。

Lets say I have a class: 可以说我有一堂课:

public class Foo<T extends Base> implements Bar<T> {
    private Bar<T> wrapped;
    public void setWrapped(Bar<T> input) {
        wrapped = input;
    }
}

If I call it with: 如果我用以下方式调用它:

//Lets just assume methods getNewVal and getFoo exist
Bar<? extends Base> val = getNewVal();
Foo<? extends Base> foo = getFoo();
foo.setWrapped(val);

The compiler says foo.execute(val) is an error. 编译器说foo.execute(val)是错误。 With a message along the lines of The method setWrapped(Bar<capture#20-of ? extends Base>) in the type Foo<capture#20-of ? 带有一条消息,类型为Foo <capture#20-of?的方法setWrapped(Bar <capture#20-of?extended Base>)。 extends Base> is not applicable for the arguments (Bar<capture#22-of ? extends Base>) . extend Base>不适用于参数(Bar <capture#22-of?extended Base>)

If I try to change Foo to be 如果我尝试将Foo更改为

public class Foo<T extends Base> implements Bar<T> {
    private Bar<T> wrapped;
    public void setWrapped(Bar<? extends Base> input) {
        wrapped = input;
    }
}

The call to foo.setWrapped(val) no longer errors. foo.setWrapped(val)的调用不再出错。 Instead wrapped = input is an error with a message along the lines of Type mismatch: cannot convert from Bar<capture#1-of ? 相反, 包装=输入是错误消息,并带有类型不匹配的消息:无法从Bar <capture#1-of转换? extends Base> to Bar<T> . 将Base>扩展到Bar <T>

What am I doing wrong? 我究竟做错了什么? Is there not a way to get the compiler to be okay with a call like this without casting? 有没有办法让编译器在不进行强制转换的情况下可以通过这样的调用正常运行?

It looks like what you want is 看起来你想要的

public class Foo {
    private Bar<? extends Base> wrapped;
    public void setWrapped(Bar<? extends Base> input) {
        wrapped = input;
    }
}

It's not clear what the Bar interface Foo needs to implement is, though, and why Foo should have a Bar as well as be a Bar . 目前还不清楚是什么Bar接口Foo需要实现的,但是,为什么Foo应该有一个Bar以及 Bar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM