Nov 08

Reflection with generics and annotation introspection

So I ran into an issue today that cost me an hour scouring documentation on reflection to see how it behaves with generics only to not find any sensible info and rather find some blog posts from folks that experienced similar issues. The basic idea is that reflection and generics or rather reflection and runtime type binding doesn’t work as some might expect. Well, at this time of the night, code speaks better than words to me, so here is a small example…

Compiling and running above with assertions enabled will throw the java.lang.AssertionError. Why one might as, well that’s because although the reflection package seems to locate the method using supertype arguments in place of actual types, this must yield some different runtime binding of that method, since introspecting for an annotation of that method yields nothing.

I’m not sure what the intention of this is and whether it’s my lack of understanding the reflection APIs and how they introspect runtime types. I’ll do more digging over the weekend and report if I find something interesting. For now the only way this can be resolved unfortunately is by writing a dynamic search method that will find the right method based on its name and argument types. The types can be supertypes, as we dynamically compare the method argument types to the required types using Class#isAssignableFrom(Class) method. Here is a util method that takes care of locating the annotation…


Leave a comment