dimanche 15 avril 2018

Why would one use reflection to get the type of a generic parameter at runtime?

I was thinking about what trying to get the type of a generic parameter despite type erasure in Java involves. There are many questions about that (ex. Get type of a generic parameter in Java with reflection, Get generic type of class at runtime) and basically two answers:

Thus, if you want the type at runtime, you have to either use the usual (and near idiomatic) workaround (see EnumMap for instance):

Class<T> MyClass {
    public MyClass(Class<T> clazz) {
        this.clazz = clazz;
    }

    ... // use this.clazz

}

Or use reflection:

Class<T> MyClass {
    public MyClass() {
        // there are some possible refinements here
        this.clazz = (Class<T>) ((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    ... // use this.clazz

}

Now I'm wondering why would one use reflection instead of the usual workaround? (I think the usual workaround is more clear than reflection.)

I assume that you have control over the source code of the generic class, and thus exclude the kind of situation where you would have used reflection anyhow (e.g. the Jackson library that converts POJOs to JSON).





Aucun commentaire:

Enregistrer un commentaire