Instantiating object from generic type: Java vs. .Net
2 min read
2 min read
public static class ProcessorThis is a pretty straightforward class, although not so meaningless if left in this way. You may use this piece of code as follows:
{
public static TItem CreateInstance<TItem>() where TItem:new()
{
TItem result = new TItem();
return result;
}
}
class ProgramNothing strange so far. What I want to show however is how simple it is to create an instance of a generic type in C#.
{
static void Main(string[] args)
{
Test t = Processor.CreateInstance<Test>();
Console.Write(t.SomeInt);
}
}
class Test
{
public int SomeInt { get; set; }
public Test()
{
SomeInt = 3;
}
}
public class Processor {Probably that's what you would write or better, would like to write since this will give you a nice compiler error. You cannot do "new T()" where T is a generic type parameter. So now the challenge starts. How can I create an instance. It turns out that you need the class for doing so s.t. it looks like
public static <T> T createInstance(){
T t = new T();
return t;
}
}
public class Processor {And then you invoke it like
public static <T> T createInstance(Class clazz) throws InstantiationException, IllegalAccessException{
T t = (T) clazz.newInstance();
return t;
}
}
public class MainClass {Note in Java you don't have to pass the generic type. The compiler will understand it outmatically. That's nice. However when looking at the overall solution, the C# example seems much more elegant. If you look at the "createInstance" method in the Java example you may also note that providing the class is somehow a duplicate information. If you're a clean-code fanatic like myself the immediate thought would be to somehow get this information form the generic parameter type directly. Through reflection? It turns out that to be a major challenge. Java has a mechanism called type erasure, which eliminates generics information at runtime in order to stay backward compatible. Read this article for more information.
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
Test t = Processor.createInstance(Test.class);
System.out.println(t.getSomeInt());
}
}