Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java get collection by generic type

Tags:

java

generics

Let's say I have my class Context like this.

public class Context {
    Set<A> sA;
    Set<B> sB;
    Set<C> sC;
}

Then I have a generic class Performer, that wants to perform operations based on the generic type from the Context class, in the following way - not possible in Java.

public class Performer<T> { // T can be type of A,B or C

   public void saveToSet(T t) {
       Context.Set<T>.add(t); 
   }
}

Then, if I say something like saveToSet(B b), the right set from the Context will be called, in this case sB (Set<B>) and the new instance will be added to that set.

Ok, the question... How do to this in Java? :D

like image 559
zwiebl Avatar asked Aug 17 '16 10:08

zwiebl


1 Answers

Sadly such an approach will not work in Java due to type erasure.

Essentially all the runtime will see is Context.Set<java.lang.Object>.add(t); and the collapse of your fields to Sets of java.lang.Objects, and so it will be unable to disambiguate.

You could work around this by writing overloads like saveToSet(A a), saveToSet(B b) etc.

In many ways, including this one, Java generics are the poor cousin of C++ templates.

like image 92
Bathsheba Avatar answered Sep 20 '22 13:09

Bathsheba