Assuming the following class stub:
public class Foo<T> { private Class<T> type; public Foo<T> () {} }
Can I store the generic type T into the field type in the constructor, without changing the constructor’s signature to ‘public Foo<T> (Class<T> type)‘?
If yes, how? If no, why?
‘type = T‘ doesn’t seem to work.
No – type erasure means that you have to provide something at execution time. You could provide either an instance of
TorClass<T>but the class itself will just have every occurrence of T replaced withObject.This kind of thing is one of the biggest disadvantages of Java’s generics vs those in .NET. (On the other hand, the variance story is stronger – if more confusing – in Java than in .NET.)