tags:

views:

194

answers:

3

question deleted

+2  A: 

You want to pass in ANY class, and get an instance of that type -- statically, i.e. without reflection? Nope, that's not possible -- due to type erasure, right.

The only way to pass in ANY class is to pass it as a parameter:

Object getInstance(Class clz){ ... };

Even if you define it as

Object getInstance(Class<T> clz){ ... };

T is lost at runtime. All you have is class. I suppose language designers could make it sweeter by allowing things like:

new T()

which under the hood would do clz.newInstance(), but they didn't.

Vladimir Dyuzhev
ah, sorry for the short explanation in the question. i edited it
Schildmeijer
`new T()` is not allowed since it assumes that a visible no-arg constructor exists, which is not true to all variations of `T`, and not enforceable using the Java type mechanism.
Robert Munteanu
if default ctor doesn't exist, just throw an exception in runtime. It would be just a syntax suger for Class.newInstance(), after all.
Vladimir Dyuzhev
+1  A: 

You could do something like the following:

public static <T> T getInstance(Class<T> klass) {
    try {
        return klass.newInstance();
    } catch (Exception ex) {
         //Do some real error handling here probably
         return null;
     }
 }
aperkins
+1  A: 

Hm ... to fully answer your question, a little background is required:

Erasure means that actual type parameters are not included in bytecode, and hence the dynamic type of a type parameter is unknown at runtime, making it generally impossible to instanciate it. (Which is why new T() for a type parameter T does not compile.)

However, actual type parameters specified in declarations of fields, methods or classes are recorded in the class file, and available to reflection. Under certain circumstances, the latter information is sufficient to determine to value of the type parameter.

For instance, the snippet from the hibernate website, if declared in class C<T>, infers the actual type of T if getClass() is a direct and non-generic subclass of C, by reflecting on the extends clause of that class' declaration. (If that extends clause however contained another type variable as in class D<T> extends C<T>, the method would throw a ClassCastException when attempting to cast a type variable to Class<?>).

If is possible to generalize that snippet to work for any non-generic getClass() (direct or otherwise), but if getClass() is generic the limited information the runtime retains about type parameters is insufficient to determine the type.

meriton