Friday, March 18, 2011

Reflection API gripes

java.lang.Method and java.lang.Constructor are strikingly close in concept. For all intents and purposes Constructors are little more than syntactic sugar. Yet there is no API acknowledgement of many their similarities.

Yes, they share some common interfaces and the same super class, but when you peal away the methods that are not accounted for by interfaces and superclasses, here's what you get:

java.lang.reflect.Constructor
public T newInstance(Object ... initargs)
public Annotation[][] getParameterAnnotations()
public Class[] getExceptionTypes()
public Class[] getParameterTypes()
public String toGenericString()
public Type[] getGenericExceptionTypes()
public Type[] getGenericParameterTypes()
public boolean isVarArgs()
java.lang.reflect.Method
public Object getDefaultValue()
public Object invoke(Object obj, Object... args)
public Class getReturnType()
public boolean isBridge()
public Type getGenericReturnType()
public Annotation[][] getParameterAnnotations()
public Class[] getExceptionTypes()
public Class[] getParameterTypes()
public String toGenericString()
public Type[] getGenericExceptionTypes()
public Type[] getGenericParameterTypes()
public boolean isVarArgs()
Of the methods, few are actually truly unique to that class type. Those would be the following methods

java.lang.reflect.Constructor
public T newInstance(Object ... initargs)
java.lang.reflect.Method
public Object getDefaultValue()
public Object invoke(Object obj, Object... args)
public Class getReturnType()
public boolean isBridge()
public Type getGenericReturnType()
A far smaller number, especially for Constructor. The remaining methods shared, but not accounted for in any superclass or interface, are:

Identical
public Annotation[][] getParameterAnnotations()
public Class[] getExceptionTypes()
public Class[] getParameterTypes()
public String toGenericString()
public Type[] getGenericExceptionTypes()
public Type[] getGenericParameterTypes()
public boolean isVarArgs()
These methods are just begging for an interface. Perhaps ParameterizedMember would be a good name?

Granted most Java development doesn't involve the reflection api, but those of us that do use it would really appreciate being thrown a bone. Especially with the growing amount of code and APIs that involve annotations. An interface similar to AnnotatedElement that can contain this critical getParameterAnnotations method would just be wonderful.

I'm quite certain there must have been some kind of debate. Likely one that ended in, "it's not really that important." Would love to hear from anyone involved.

I personally can't think of any downside to allowing us developers who deal with the guts of supporting annotation based APIs to get a little polymorphism in this are of the reflection API.

A bottle of my favorite rum to whomever can get this into Java 7.