Factory Design Pattern with Java generics

I was wondering if it was possible to implement the factory pattern using a generic like sintax with java5. Something like:

IFactory factory = new ConcreteFactory();

Car c=factory.CreateObject<Car>();

I saw this article the other day http://weblogs.asp.net/pgielens/archive/2004/07/01/171183.aspx

done in C# for the framework 2.0 and tryed to re-implement it with java5 however I was less then fortunate, can someone do a functional conversion?

[481 byte] By [schrepflera] at [2007-10-1 0:57:06]
# 1
Object theObject = Class.forName( className ).newInstance() ;
MartinS.a at 2007-7-8 1:16:53 > top of Java-index,Other Topics,Patterns & OO Design...
# 2
http://hookom.blogspot.com/2004/12/factory-pattern-w-delegates.html http://forum.java.sun.com/thread.jspa?forumID=316&threadID=566247
hookomjja at 2007-7-8 1:16:53 > top of Java-index,Other Topics,Patterns & OO Design...
# 3
> Object theObject = Class.forName( className> ).newInstance() ;What's the point of using a generic factory if one can't avoid using Object :)
schrepflera at 2007-7-8 1:16:53 > top of Java-index,Other Topics,Patterns & OO Design...
# 4

> > Object theObject = Class.forName( className

> > ).newInstance() ;

>

> What's the point of using a generic factory if one

> can't avoid using Object :)

You can avoid using Object. You could just as easily use a common base or interface to implement you factories create method.

i.e somehting along these lines.

public Car createCar( String className)

{

return (Car) Class.forName( className ).newInstance() ;

}

I usually also use a Properties or XML file to map abstract names to actual class names in my factory.

MartinS.a at 2007-7-8 1:16:53 > top of Java-index,Other Topics,Patterns & OO Design...
# 5

I had to change the signature a bit but this is the best I came with:

(I don't like I have to write Type.class but if someone has a better idea please share, I deliberatly used classes are return types but you can easily program to the interfaces as well)

use:

ConcreteFactory cf=new ConcreteFactory();

Car c=cf.Create(Car.class);

public interface Vehicle {

String getName();

}

public class Plane implements Vehicle {

String name="Mig 29";

public String getName() {

return name;

}

}

public class Car implements Vehicle {

String name="Volvo";

public String getName() {

return name;

}

}

public interface IFactory{

<T> T Create(Class<T> type);

}

public class ConcreteFactory implements IFactory {

public <T extends Vehicle> T Create(Class<T> type) {

try {

return type.newInstance();

} catch (InstantiationException e) {

return null;

} catch (IllegalAccessException e) {

return null;

}

}

}

schrepflera at 2007-7-8 1:16:53 > top of Java-index,Other Topics,Patterns & OO Design...