3

首先让我为糟糕的标题道歉,但我不知道如何用一句话来概括这一点。

public class GenericFun {
    public class TypedStream<I extends OutputStream> {
        I input;

        public I getInput() { return input; }
        public void setInput(I input) { this.input = input; }
    }

    public abstract class GarbageWriter<I extends OutputStream> {
        public void writeGarbage(I output) throws Exception {
            output.write("Garbage".getBytes());
        }
    }

    public class GarbageWriterExecutor<I extends OutputStream> extends GarbageWriter<I> {
        public void writeTrash(TypedStream stream) throws Exception{
            this.writeGarbage(stream.getInput());       // Error
            this.writeGarbage((I)stream.getInput());    // OK
        }
    }
}

在上面的代码中(OutputStream 只是一个示例),GarbageWriterExecutor方法中的类类中的第一行会导致编译错误,而第二行不会。我对此有两个问题。

  1. 为什么stream.getInput()会导致错误,即使TypedStream.I已知扩展OutputStream
  2. 如果没有丑陋的铸造,我该如何解决这个问题?
4

4 回答 4

4

因为你的方法

public void writeTrash(TypedStream stream)

还应确保TypedStream定义类型,如下所示:

 public void writeTrash(TypedStream<I> stream)

编辑:托马斯回答实际上解释了原因

TypedStream 流将禁用泛型类型检查,因此编译器只知道 getInput() 将返回一个对象,因此会出现错误。

于 2013-10-02T14:13:35.063 回答
3

TypedStream stream将禁用泛型类型检查,因此编译器只知道getInput()将返回一个对象,因此会出现错误。

试试writeTrash(TypedStream<I> stream)吧。

也许您想要使用writeTrash(TypedStream<? extends I> stream)以便能够传递任何TypedStream参数化II.

另一种选择是

public class GarbageWriterExecutor extends GarbageWriter<OutputStream> {
  public void writeTrash(TypedStream<?> stream) throws Exception{
    this.writeGarbage(stream.getInput());     
  }
}

或者

public class GarbageWriterExecutor extends GarbageWriter<OutputStream> {
  public void writeTrash(TypedStream<? extends OutputStream> stream) throws Exception{
    this.writeGarbage(stream.getInput());     
  }
}
于 2013-10-02T14:13:36.777 回答
1

只需使用:

public class GarbageWriterExecutor<I extends OutputStream> extends GarbageWriter<I> {
    public void writeTrash(TypedStream<I> stream) throws Exception {
        this.writeGarbage(stream.getInput());
    }
}

即参数化你的TypedStream参数I

于 2013-10-02T14:14:15.503 回答
0
1.Resolve this by using this code.

 public void writeTrash(TypedStream<I> stream) throws Exception{
            this.writeGarbage(stream.getInput());       
            this.writeGarbage(stream.getInput());   
        }
2.  In Generic class class name is followed by a type parameter section. If you are not    doing this then you have to do casting.
于 2013-10-02T14:30:05.000 回答