Archive for July, 2009

Type Safe Enumeration with Java Generics

Tuesday, July 28th, 2009

I’ve been working with Java 5 Generics for about one year now and one pattern that emerged from my experience is the use of generics to create enumerations that provide type safety (I don’t claim to be the inventor of that pattern, actually I don’t even claim it is a pattern).

Often type safety can be achieved by using method type variables like

public abstract <N extends Number> createNumber(Class<? extends N> numberType, String stringValue);

The drawback of this solution is that all the classes must belong to the same hierarchy, in that example they all need to be a subclass of java.lang.Number. The most direct workaround is to free the type variable from its upper bound java.lang.Number. That makes the choice very large since any subclass of java.lang.Object can be accepted.

It is also impossible to prevent some subclass to be used as type argument at compilation time. Failure would have to happen at runtime with an java.lang.IllegalArgumentException thrown for instance.

Those two limitations makes the method not easy to understand the first time you see it, specially when it is part of an API, and it is not possible to make it type safe (actually not as far as I know :-) ) as Java Enums cannot be used as a generic declaration.

So I had to find a way to express an enumerated type that would be type safe. The solution I found is actually not an enumeration in the old/classic way we use to know it before Java 5 Enums (i.e it is class that has a private constructor with public static fields) and therefore it cannot be used in a switch statement. That probably is the only drawback I found but it is a more acceptable issue than the two problems I had before.

Let’s assume we represent a concept of simple types which are arbitrarily defined by String, Boolean and Integer with

public class SimpleType<S> {

   public static final SimpleType<String> STRING =
      new SimpleType<String>(String.class);

   public static final SimpleType<Integer> INTEGER =
      new SimpleType<Integer>(Integer.class);

   public static final SimpleType<Boolean> BOOLEAN =
      new SimpleType<Boolean>(Boolean.class);

   private final Class<S> javaType;

   private SimpleType(Class<S> javaType) {
      this.javaType = javaType;
   }
}

Now we can easily use it as a type safe enumeration, for instance here is how I would write a parse method:

/*
 * Note : yeah this is not really OO and it could be
 * possible to have an abstract parse(String s)
 * method on the SimpleType class and have the static
 * method delegate to it. I leave it as an exercise
 * for the reader.
 */
public <T> T parse(SimpleType<T> simpleType, String s) throws NullPointerException {
   if (simpleType == null)
      throw new NullPointerException("No null simple type is accepted!");
   if (s == null)
      throw new NullPointerException("No null string can be parsed!");
   if (simpleType == SimpleType.STRING)
      return s;
   if (simpleType == SimpleType.INTEGER)
      return Integer.valueOf(s);
   if (simpleType == SimpleType.BOOLEAN)
      return Boolean.valueOf(s);
   throw new AssertionError("impossible!);
}

This way we enforce the set of types that can be passed as arguments in our method and we do it in a manner that will enforce the developer to write type safe code.

Next time I’ll show you have it is possible to improve the pattern efficiency and usability by adding methods on the Type Safe Enumeration class.

Advanced Java reflection framework needs a (good enough) name

Friday, July 17th, 2009

I have been working during the past few days on a reflection framework for Java. Beside the complexity of the actual reflection layer, the developer is pretty much left to himself to perform advanced operations such as type variable resolution or annotation discovery based on the type inheritance hierarchy.

Furthermore this reflection framework is implemented with the runtime java reflection API (java.lang.reflect.Type and its implementations) and the compile time java reflection API (javax.lang.model.type.*). It means you can perform compile time reflection or runtime reflection with the same code. I forgot to mention that the java compile time API is awful.

The first reason I wrote this framework was to perform type variable resolution based on a specific class. I needed to perform such operations for a new project (that I will announce soon, stay tuned).

Let me give you an example:

public class A<V> {

  private final V value;

  public A(V value) {
    this.value = value;
  }

  public V getValue() {
    return value;
  }

public class B extends A<String> {
  public B(String value) {
    super(value);
  }
}

Now if we want to know what is the value of the type variable V at runtime for the class B, the code to perform the resolution is pretty tricky to write and requires a fairly good knowledge of the java type system, although it’s a very intuitive operation to do. Let me give you another example:

public class Event<S> {

  private S source;

  public Event(S source) {
    this.source = source;
  }

  public S getSource() {
    return source;
  }

}
public interface Listener<S> {

  void onEvent(Event<S> event);
}

public class FooListener implements Listener<String> {
  void onEvent(Event<String> event);
}

Although we all know that Java type erasure will not give us the type of S at runtime from instances of the Event class, any implementation of the Listener interface will carry the information about the type variable. Note that it may not be possible to resolve it if the subclass does not bind the variable to a type. It is therefore possible for the framework broadcasting events to know if a listener is able to receive events from a particular source.

Since Java 6 it becomes very easy to process source code at compile time (as exhibited by Gavin King during his researches about the type safe criteria API for JPA). For instance it would be possible to replace the need for CGLib at runtime by a library that would perform a similar work at compile time (actually I wrote pretty much that in the forthcoming project). The advanced Java reflection framework helps to hide the java compile time reflection API. The compile time API is source code oriented but does expose the same semantics as the runtime API.

Another neat feature is the resolution of annotations along a type hierarchy which is very useful if you want to determine the annotation of a type or a method taking in account the type hierarchy. Very useful in the following situation

@Foo
public interface A {
  @Bar void m();
}

public class B implements A {
  public void m() {
  }
}

Finally the framework has some nice stuff coming in, such as the inclusion of the visitor pattern that allows you to perform an operation along the hierarchy of a type, the obtention of the raw class type of any type which attempts to unify the raw type of a parameterized type and the elimination of the synthetic methods due to the return type covariance.

I plan to host that reflection framework project soon somewhere (under LGPL) because I think it will be useful to anyone performing advanced operations with the Java reflection. What is missing for now is a decent name for the project since I haven’t been able to come up with something nice. If you have a good suggestion, don’t hesitate to send me an email (go on www.julienviet.com for the @).