Hacker News new | past | comments | ask | show | jobs | submit login

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.



There are cases when reified generics are a giant pain in the butt and non-reified ones are the right solution. See Scala or F# and .NET interoperability.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: