views:

81

answers:

4

Hi,

I have a parameterized class :

class ParameterizedClass<T extends AbstractSomething> { }

calling:

new ParameterizedClass<Something>();

So how can I get actual type Something of T by using Java Generics?

+1  A: 

You could use this trick in your constructor: (see http://www.hibernate.org/328.html)

Class<T> parameterType = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];

But I believe this code only works when the class is sub-classed and an instance of the sub-class executes it.

Adrian Pronk
I know this trick and am using on DAO classes. But this is not what I'm looking. To use this trick, I guess, we have to define actual value of generic type of parent class on sourcecode. GenericDAO<T extends Model>UserDAO extends GenericDAO<User>
TanerDiler
+2  A: 

If you mean just from the object itself, you can't. Type erasure means that information is lost.

If you have a field which uses the parameterized type with a concrete type argument though, that information is preserved.

See Angelika Langer's Generics FAQ, and particularly the section on type erasure.

Jon Skeet
+5  A: 

Due to type erasure, this isn't possible in Java, unfortunately.

What I recommend in these circumstances, is to create a class as follows:

class ParameterizedClass<T> {
    private Class<T> type;

    /** Factory method */
    public static <T> ParameterizedClass<T> of(Class<T> type) {
        return new ParameterizedClass<T>(type);
    }

    /** Private constructor; use the factory method instead */
    private ParameterizedClass(Class<T> type) {
        this.type = type;
    }

    // Do something useful with type
}

Due to Java's type inference for static methods, you can construct your class without too much extra boilerplate:

ParameterizedClass<Something> foo = ParameterizedClass.of(Something.class);

That way, your ParameterizedClass is fully generic and type-safe, and you still have access to the class object.

jqno
A: 

This is a mostly problematic topic, since it only works under certain conditions like expected (expecially in complex scenarios).

But Xebia published a good article on the whole thing.

Johannes Wachter