|
|
|
|
|
by snuxoll
4518 days ago
|
|
That's precisely how the JVM behave, which aggravates a lot of people when writing code using generics. In C# I can do the following: public T getInstance<T>() {
return this.Instances[typeof(T)];
}
Or, even better: public T createInstance<T>() {
return new T();
}
Meanwhile Java requires this: public <T> T getInstance(Class<T> cls) {
return this.instances[cls];
}
The type information above (the generic parameter T) is stripped after compilation, so the Class parameter is needed on the method to get a solid reference to the type we need to work with at run-time. This gets worse when we want to do the second example. public <T> T createInstance(Class<T> cls) {
return cls.newInstance();
}
It gets even more fun when you throw in non-default constructors. Non-reified generics are a giant pain in the butt. |
|