Yesterday I was working on dynamic mapping of marshallers to their marshalled type. The way I’ve done it was having an interface Marshaller
with generic parameter <T>
. Then I was using Reflections to get all classes that implements this interface. Then I needed to get the actual type of <T>
which is a problem if there is for example an abstract class that is the base for all marshallers. So if you have the following setup, it’s not as easy as just calling ParameterizedType#getActualTypeArguments()
.
interface Marshaller<T> {
...
}
abstract class AbstractMarshaller<T> implements Marshaller<T> {
...
}
class BooleanMarshaller extends AbstractMarshaller<Boolean> {
...
}
So I have written the following method that resolves actual types of all generic parameters of a given class.
And you’d use it like this:
Map<TypeVariable, Type> params = genericParameters(Marshaller.class, BooleanMarshaller.class, null);
And the params
map would have exactly one entry, (TypeVariable) "T" => (Class) Boolean
.
I wrote this because I was unable to find the solution anywhere else, so hopefully this will help someone in the future.
Originally published at www.tadeaskriz.com on April 11, 2014.