How do I get a class instance of generic type T?
Instantiating a generic type T
is done by passing its Class<T> reference to the method that will create the object. Invoke newInstance()
using the class reference to create an object of T
.
Example:
Wrestling Java's type erasure
Despite Java's type erasure knocking out specific type information from generics at compile-time, you can use reflection to punch above its weight:
- ParameterizedType: Documents all the colourful types (e.g.,
List<String>
). - Anonymous subclass: A snazzy way to keep hold of runtime type info.
Getting your hands dirty: Practical usage
Harness the power of Spring's GenericTypeResolver
If you've got Spring Framework on your team, you can pass the ball to GenericTypeResolver
to handle heavy-duty type resolution:
When Spring isn't in season
When Spring isn't blooming, consider crafting your own non-generic subclass or utility method to suit your generic needs:
Be safe out there!
- ClassCastException: Stay safe - fend it off using try-catch blocks.
- Reflection: Play nice with
getClass().getGenericSuperclass()
or face the wrath! - Type info storage: A neat trick for future you to thank past you.
Master the Art of Reflection
Birth of a new object
In need to breathe life into a class from its string representation? Class.forName()
is your guardian angel:
Playing the field: Other tactics and considerations
Class literal shenanigans
Pepper your APIs with Class literals to flavor your generics:
Array of Everything
Jump the hoop and create a generic array, with all its type T
goodies:
Cementing roots: Abstract classes
Employ abstract classes for Class of T
and bake in abstract methods:
Every problem, every solution
Tailor your approach to your needs - use Class<T> or reflection based on the problem at hand.
Was this article helpful?