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

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-31 03:46   11   0

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

public class GenericFun {

public class TypedStream {

I input;

public I getInput() { return input; }

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

}

public abstract class GarbageWriter {

public void writeGarbage(I output) throws Exception {

output.write("Garbage".getBytes());

}

}

public class GarbageWriterExecutor extends GarbageWriter {

public void writeTrash(TypedStream stream) throws Exception{

this.writeGarbage(stream.getInput()); // Error

this.writeGarbage((I)stream.getInput()); // OK

}

}

}

在上面的代码(OutputStream只是一个例子)中,类GarbageWriterExecutor类在方法第一行导致编译错误,而第二行则没有.我有两个问题.

>为什么stream.getInput()会导致错误,即使已知TypedStream.I扩展OutputStream?

>如果没有丑陋的演员,我怎么能解决这个问题呢?

解决方法:

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

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

也许你的事件想要使用writeTrash(TypedStream stream),以便能够传递为I或I的子类参数化的任何TypedStream.

还有另一种选择

public class GarbageWriterExecutor extends GarbageWriter {

public void writeTrash(TypedStream> stream) throws Exception{

this.writeGarbage(stream.getInput());

}

}

要么

public class GarbageWriterExecutor extends GarbageWriter {

public void writeTrash(TypedStream extends OutputStream> stream) throws Exception{

this.writeGarbage(stream.getInput());

}

}

标签:java,inheritance,generics

来源: https://codeday.me/bug/20190725/1532924.html

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP