0

I have read quite a bit on type erasure and explicit variance/covariance of generics but I still can't fully understand why this is an unsafe cast:

public interface TestRepository<T extends ParentEntity> extends JpaRepository<T, String> {
   List<T> testMethod();
}

public class TestClass() {

  private TestRepository testRepository;

  public void test() {
     List<? extends ParentEntity> entities = testRepository.testMethod(); //not safe
     testRepository.saveAll(entities); //safe

  } 
}

Now I can get this to be safe by using a wildcard on the TestRepository field, but then I get a problem with the saveAll method of Jpa:


public class TestClass() {

  private TestRepository<? extends ParentEntity> testRepository;

  public void test() {
     List<? extends ParentEntity> entities = testRepository.testMethod(); //safe
     testRepository.saveAll(entities); //not safe

  } 
}

What is the best way to make this work without making the TestClass generic?

Bgtop
  • 21
  • 5
  • 2
    Not too sure whether the heart of your question is related to the fact that `TestRepository testRepository` declares a raw type. But you should probably start by reading through answers on [this question about raw types](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – ernest_k Mar 11 '20 at 11:22
  • I understand that the raw type shouldn't be used, hence the second example I have given uses a wildcard. However, I can't seem to get it to work with the saveAll method, which has the following signature: ` List saveAll(Iterable var1)` Is there any way to get this working? – Bgtop Mar 11 '20 at 12:00
  • *"I have read quite a bit on type erasure and explicit variance/covariance of generics"* ... just clarifying: in Java, while arrays are reified and covariant, generics are erased and *invariant*. – scottb Mar 11 '20 at 14:08

0 Answers0