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?
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?
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.
Generics in Java are generally more powerful than in C#.
If you want to construct an object but without hardwiring a constructor/static method, use an abstract factory. You should be able to find detailed information and tutorials on the Abstract Factory Pattern in any basic design patterns book, introduction to OOP or all over the interwebs. It's not worth duplicating code here, other than to mention that Java's closure syntax sucks.
IIRC, C# has a special case for specifying a generic type has a no-args constructor. This irregularity, by definition, presupposes that client code wants to use this particular form of construction and encourages mutability.
Using reflection for this is just wrongheaded. Generics in Java are a compile-time, static-typing feature. Attempts to use them at runtime are a clear indication of something going wrong. Reflection causes verbose code, runtime failures, unchecked dependencies and security vulnerabilities. (
Class.forName
is particularly evil.)I could do this in a JUnit Test Setup.
I wanted to test a Hibernate facade so I was looking for a generic way to do it. Note that the facade also implements a generic interface. Here T is the database class and U the primary key.
Ifacade<T,U>
is a facade to access the database object T with the primary key U.