繁体   English   中英

将泛型类型作为Java中的泛型方法参数传递

[英]Passing generic types as generic method parameters in Java

首先让我为可怕的头衔道歉,但我不知道如何用一句话来总结这一点。

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. 如果没有丑陋的演员,我怎么能解决这个问题呢?

因为你的方法

public void writeTrash(TypedStream stream)

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

 public void writeTrash(TypedStream<I> stream)

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

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

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

尝试使用writeTrash(TypedStream<I> stream)

也许你的事件要使用writeTrash(TypedStream<? extends I> stream) ,以便能够通过任何TypedStream这是对参数I或子类I

还有另一种选择

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());     
  }
}

只需使用:

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

即用I参数化你的TypedStream参数。

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.

暂无
暂无

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

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