I know Java’s generics are somewhat inferior to .Net’s.
I have a generic class Foo<T>, and I really need to instantiate a T in Foo using a parameter-less constructor. How can one work around Java’s limitation?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
One option is to pass in
Bar.class(or whatever type you’re interested in – any way of specifying the appropriateClass<T>reference) and keep that value as a field:Another option is to have a “factory” interface, and you pass a factory to the constructor of the generic class. That’s more flexible, and you don’t need to worry about the reflection exceptions.