我有通用类:public class MyGenericClass<T> { T get(){ return T; } ...}有2个类:public class CatService{ MyGenericClass<Cat> generic; public CatService(MyGenericClass<Cat> generic){ this.generic = generic; }}public class DogService{ MyGenericClass<Dog> generic; public DogService(MyGenericClass<Dog> generic){ this.generic = generic; }}我认为最好创建public abstact class Service:public abstract class Service { MyGenericClass generic; public MyGenericClass (MyGenericClass generic){ this.generic = generic; }}并使CatService和DogService 扩展这个抽象服务。他们将在调用super(MyGenericClass generic)或super(MyGenericClass generic)的构造函数中初始化泛型字段。但是在这种情况下,当我尝试调用 MyGenericClass 方法时,我收到“unchecked call”,当我尝试调用 T get() 时,我必须使用(Cat) generic.get() OR (Dog) generic.get();有可能避免吗?更新:需要指定泛型类型:extends Service<Cat>public class CatService extends Service<Cat> { public CatService(MyGenericClass<Cat> generic){ super(generic); }}public abstract class Service<T> { MyGenericClass<T> generic; public MyGenericClass (MyGenericClass<T> generic){ this.generic = generic; }}
1 回答
翻阅古今
TA贡献1780条经验 获得超5个赞
使Service类也通用。
public abstract class Service<T> {
MyGenericClass<T> generic;
public MyGenericClass (MyGenericClass<T> generic){
this.generic = generic;
}
}
添加回答
举报
0/150
提交
取消