Saturday, August 2, 2008

Instantiation of the Generic Type

I spent recently a few hours trying to figure out how to Instantiate Generic Type in Java.

In C# this would looks like this:

public static T CreateObject<T>()
{
Type type = typeof(T);
return (T)Activator.CreateInstance(type);
}


In Java it is not very clear, and I tend to believe it is simply impossible to do with such a simplicity.
The closest solution I've come to is:

public static <T> T createObject(Class<T> clazz){
return (T) clazz.newInstance();
}


As you can see in java I have to actually pass a class as a parameter, which I do not like. No big deal of course but from pure philosophical point of view this sucks.
Why is this a problem in java? Because of the type erasure? I guess so. BTW here is a very interesting article about Generics in Java, C#, C++ (Templates)


More on this topic... a little bit later...

No comments: