Besides the issue of type erasure -- which makes this impossible in any event -- you simply can't guarantee that T
has an exposed, no-argument constructor!
The traditional workaround is to pass around factory objects that provide methods that can be used to obtain T
objects. A simplistic example would be
interface Factory<T> {
T create();
}
and then your class can get a Factory<T>
and call create()
on it to get more T
s. More sophisticated examples might require additional arguments to a create
method, for example, or overloads.
Less-pretty workarounds include explicit reflection, passing around Class<T>
objects. For example, ArrayList.class.newInstance()
returns a newly constructed raw ArrayList
. You have to explicitly pass around the Class
object, and the reflection-based approach is slower than a normal constructor or a factory object (even though the speed of reflection has been improving lately). You also depend on the class exposing a no-arg constructor, which isn't always the case. It can be made to work, but it's never what I'd call "pleasant."
(That said, for reference, there are indications that the situation may change somewhat in Java 8 with Project Lambda and friends.)