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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With