vendredi 28 août 2015

How can I get at runtime the type of a wildcard upper bound?

Suppose I am keeping a registry of subclasses of a certain class, T:

public class ClassRegistry<T> { Set<Class<? extends T>> klasses; ... public void register(Class<? extends T> klass) { klasses.add(klass); }

You register yourself with a call like registry.register(this.getClass()). I would like to make this simpler with a method on ClassRegistry<T> where you just pass yourself, this, e.g., registry.register(this):

public void register(Object obj) { Class<?> klass = obj.getClass(); this.register(klass); }

Oops, this is wrong, because it calls itself (matching the overload with parameter type Object and not, of course, Class<? extends T>). So, instead:

public void register(Object obj) { Class<? extends T> klass = obj.getClass(); this.register(klass); }

And now of course that doesn't compile because the compiler doesn't know that your obj is actually of some type ? extends T. And it might not, at that, because the caller might be wrong.

So my question is: How do I test/validate that obj is a subclass of T which is a wildcard upper bound (so I can safely cast)? (I suspect - or maybe, hope - the answer involves Guava's TypeToken, which is why I added the Guava tag, but I'll take any answer, thanks!)





Aucun commentaire:

Enregistrer un commentaire