Tuesday, May 11, 2010

Pitfalls of Reflection

In this post I will discuss a pitfall of the use of reflection in Java. Specifically how reflection can obscure and even change the semantics of a piece of code.

What is wrong with the following example of JavaBean naming convention?

public Boolean isCorrect() {
    /* implementation not shown. */
}

Did you spot the capital B on the Boolean return type? According to the JavaBean naming convention the property does not fall under the special rules for booleans and should be named accordingly.

public Boolean getCorrect() {
    /* implementation not shown. */
}

Although there is a sleight syntactic difference, the apparent semantic difference is non-existent. According to William Shakespeare:

A rose by any other name would smell as sweet

Enter reflection. By using reflection it is possible to perform hugely different behaviour depending on the name of a method. The following whimsical example is a clear demonstration of this fact.

Class aClass = ReflectedClass.class;
Method method;
try
{
    method = aClass.getDeclaredMethod("isCorrect");
    protect(Planet.EARTH);
}
catch (NoSuchMethodException e)
{
    destroy(Planet.EARTH);
}

So one of the pitfalls of reflection is the hidden semantics associated with code. Stated in other words: the influence of code can not be inferred by the syntactic definition of that code.

No comments:

Post a Comment