Java 中的泛型 - 使用抽象类进行类型擦除

我有通用类:


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;

   }

}


呼啦一阵风
浏览 111回答 1
1回答

翻阅古今

使Service类也通用。public abstract class Service<T> {&nbsp; &nbsp;MyGenericClass<T> generic;&nbsp; &nbsp;public MyGenericClass (MyGenericClass<T> generic){&nbsp; &nbsp; &nbsp; &nbsp;this.generic = generic;&nbsp; &nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java