Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java generics TypeReference for collection method not working

I have three classes in play here:

public class MyClass1<T, ID> {

  @Getter
  private static class IdHolder<ID> {
    private ID id;
  }
}

public class MyClass2<T> {
   public MyClass2(Class<? extends T> type) {
   }

   public List<T> fetch() {
   }
}

Inside of MyClass1, I need to create an instance of MyClass2 and call the fetch() method:

List<IdHolder<ID>> previous = new MyClass2<IdHolder<ID>>(???).fetch();

If I use raw types like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

List<IdHolder> previous = new MyClass2<>(IdHolder.class).fetch();

It does work, but then IntelliJ complains about me using raw types (obviously).

I have tried:

TypeReference<IdHolder<ID>> t = new TypeReference<IdHolder<ID>>() {};

What can I put in ??? to get the class type for IdHolder<ID> or is that just not possible due to type erasure and I have to use raw types? I thought that was the whole point of TypeReference.

>Solution :

is that just not possible due to type erasure and I have to use raw types?

That’s correct, it is not possible. You will have to use raw types.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading