开发者

How can I learn actual type argument of an generic class? [duplicate]

This question already has answers here: Get generic type of class at runtime (30 answers) Closed 3 years ago.

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 u开发者_JS百科sing Java Generics?


It can be done, but type erasure can make it very hard. As the other answers discuss, you either have to make a subclass of ParameterizedClass or add a field of type T to ParameterizedClass, and the reflection code you need to do it is convoluted.

What I recommend in these circumstances, is to work around the issue like this:

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.

EDIT: Addressed the comment


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜