Instantiating Java objects of generic type parameter

I was going to write a really grand blog entry about how to instantiate a Java object of the type specified as parameter to a generic class but I figured that someone must have done that already. The blog article Java Generics: Instantiating Objects Of Type Parameter Without Passing Class Literal To Instance sums it up pretty good. My implementation supports a deeper inheritance hierarchy (caused my Javassist in my case) but I was not clever enough to extract the hack, I mean magic, to a generic Factory class as suggested by the first comment to the article.

The final statement in the article is that This pattern is frequently used for generic DAO classes, and yes I first saw it at hibernate.org – Generic Data Access Objects, but I think it is a bit scary that this workaround is common enough to be called a pattern.

Leave a Reply

Your email address will not be published. Required fields are marked *