我有一个像这样的界面
public interface Reader<T> {
T read(Class<T> type,InputStream in);
}
它是一个通用接口(interface),旨在从流中读取T类型的对象。然后我知道我将处理的所有对象都是 S 的子类,比方说 S。所以我创建了这个
public class SReader implements Reader<S>{
S read(Class<S> type, InputStream in){
// do the job here
}
}
但是Class<S1>
无法分配给Class<S>
即使S1是S的子类。我如何优雅地实现这个?有界类型参数?我不明白这一点。我唯一的解决方案就是删除类型参数,例如
public class SReader implements Reader{
// the other stuff
}
最佳答案
听起来你想要
public interface Reader<T> {
T read(Class<? extends T> type,InputStream in);
}
关于java - 如何在Java中实现这个通用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16042867/