How generics can be used in Class Factories

Lets see how generics can be used to create generic interface for class factories.


public class GenericFactory <E>
{
Class<E> thisClass=null;

public GenericFactory (Class iclass)
{
this.thisClass = iclass;
}

public E createInstance() throws IllegalAccessException,InstantiationException{
return(E)this.thisClass.newInstance();
}
}

The <E> is a type token that signals that this class has a type set when instantiated.


public class Myclass {

void print()
{
System.out.println("Hellooo");
}
}


public class Main {

public static void main(String[] args) throws IllegalAccessException, InstantiationException {

GenericFactory<Myclass> factory = new GenericFactory<Myclass>(Myclass.class);
Myclass myclass= factory.createInstance();
myclass.print();
}
}

Output:-  Hellooo

We can see that, it is not necessary to cast the object returned from the factory.createInstance().


Comments

Popular posts from this blog

When to use getClass() and instanceOf in Java

How class.forName loads the Database Driver in JDBC

Why Time gets truncated with ResutSet getDate() function.