我有一个像这样的界面
public interface Reader<T> {
T read(Class<T> type,InputStream in);
}
Run Code Online (Sandbox Code Playgroud)
它是一个通用接口,用于从流中读取类型为T的对象.然后,我知道我会处理的所有对象的子类,让我们说小号.所以我创造了这个
public class SReader implements Reader<S>{
S read(Class<S> type, InputStream in){
// do the job here
}
}
Run Code Online (Sandbox Code Playgroud)
但是Class<S1>,Class<S>即使S1是S的子类,也无法分配.我该如何优雅地实现这一点?有界类型参数?我不是这么想的.我唯一的解决方案就是删除类型参数
public class SReader implements Reader{
// the other stuff
}
Run Code Online (Sandbox Code Playgroud)
这听起来像你想要的
public interface Reader<T> {
T read(Class<? extends T> type,InputStream in);
}
Run Code Online (Sandbox Code Playgroud)