vendredi 8 juillet 2022

Unexpected behaviour with generics

I'm facing this error while work with Java generics, and I don't understand which is the problem;
I have two classes like these:

public abstract class BaseClass{
   ....
}

public class OneClass extends BaseClass{
   ....
}

I have a generic repo for OneClass:

public class MyRepo<T extends BaseClass>{
   List<T> getElements();
}

Then I have a method that should works whit generics:

private MyRepo<OneClass> myRepo;   

public <T extends BaseClass> List<T> myMethod(){
     return myRepo.getElements();
}

The method doesn't work unless I force a cast to List ( as shown below ):

public <T extends BaseClass> List<T> myMethod(){
   return  (List<T>)  myRepo.getElements();
}

I don't understand which is the problem given that OneClass extends BaseClass.
Thanks for any suggestion.





Aucun commentaire:

Enregistrer un commentaire