I have a Factory class for creating various objects.
The API is like this:
public static <T extends BusinessEntity> T createEntity(Class<T> t)
The usage is as:
Car car = Factory.create(Car.class);
Notice I have to specy the class type as a parameter.
I note with things like the collections framework, I don't have to specify a class parameter. For example, I can just do
List<Car> cars = new ArrayList<Car>();
I was wondering is there anyway I can improve my Factory method, so I don't have to specify a .class parameter.
Thanks a million.
No, you can't really do that.
The problem is that generics are implemented with a technique called generics. Basically (and quite over-simplified) the Java runtime doesn't know a lot about generics (it only knows the upper bound, which is often simply java.lang.Object). The compiler knows more than that, but the info is not used at runtime.
That means that your createEntity() method can't actually do anything with the concrete type T, unless it also gets some runtime-visible information about it (in your case a correct Class<T> object).
The reason why ArrayList (and other collections) don't need this kind of information is that it doesn't actually create any T objects. It just stores them (and it doesn't even check if the objects are actually T, it depends on compile-time checks for that).