Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java中实现这个通用方法?_Java_Generics - Fatal编程技术网

如何在Java中实现这个通用方法?

如何在Java中实现这个通用方法?,java,generics,Java,Generics,我有一个这样的界面 public interface Reader<T> { T read(Class<T> type,InputStream in); } 听起来像是你想要的 public interface Reader<T> { T read(Class<? extends T> type,InputStream in); } 公共接口读取器{ 看不懂(ClassI不允许更改原始接口方法签名。有其他方法吗?如果Foo扩展了

我有一个这样的界面

public interface Reader<T> {
    T read(Class<T> type,InputStream in);
}

听起来像是你想要的

public interface Reader<T> {
    T read(Class<? extends T> type,InputStream in);
}
公共接口读取器{

看不懂(ClassI不允许更改原始接口方法签名。有其他方法吗?如果
Foo扩展了Bar
,并且您想从
读卡器
读取
,则不允许;您无法将
传递给
读卡器
。如果您不允许更改接口,则可能无法这是为了确保您不能读取子类而故意采取的措施。此接口和方法的用途是什么?我不明白您为什么要在读取器上指定一个类型参数,同时将类对象传递给该方法。我使用的一个库中有一个类似的接口。它用于反序列化特定的从提供的输入流中初始化。也许这只是一个故意的举动,就像下面@Louis Wasserman所说的。好吧,我在想,如果
Reader
的实例只能接受一个特定的类,那么
type
参数总是相同的,为什么要在
read()中使用class对象呢
方法?它可以在构造函数中传递,或者
Reader
的特定子类已经专门用于此类型。
public class SReader implements Reader{
    // the other stuff
}
public interface Reader<T> {
    T read(Class<? extends T> type,InputStream in);
}