Just a hypothetical question, but assuming that a generic type T has a concrete implementation and a no-arg constructor, is there a clean way to get a new instance?
David O'Meara wrote:Just a hypothetical question, but assuming that a generic type T has a concrete implementation and a no-arg constructor, is there a clean way to get a new instance?
Raymond is right. The only way to instantiate any T instance is through a Class<T>. Either use newInstance() for getConstructor(...).newInstance(...).
Similarly, the only way to instantiate any T[] is to use java.lang.reflect.Array with a Class<T>. You'll still need to do a cast, suppressing the warning, but that's safe:
The reason it is more theoretical is that it is currently a utility method used to map from a DB entity to a POJO (yes I know they can be detached, long story) for a variety of enumerated types. More or less.
I currently use it like this, which is not terribly difficult
where there are several similar types for MyValue and MyItem
I guess you want something more like where it uses type inference to determine T and instantiate it, but that's simply not possible.
Perhaps generics can be extended in the future, something like this:
Omitting the constructor argument types will then use the current situation, where instantiation is impossible.
However, because of type erasure I doubt this will ever happen. T is no longer known at run time. For this to work the methods would need to be inlined, as that's the only way to link T and its actual value. Or type erasure needs to be removed, but that would cause a lot of compatibility issues.