Archive for November, 2009

Java Reflection & Constructor Varargs

I had a spot of trouble getting reflection to work with a Vararg constructor. Without being entirely sure, I think this is because Generics are implemented by type erasure whereby the type information is only available at compile time. At runtime i.e. when the Reflection API is invoked, the type information has been erased by the compiler. It looks as though this is the case to ensure legacy backwards compatibility.

Anyway, the trick with the code below was to double-wrap the constructor argument array ‘y’ in another Object array ‘z’, which isn’t clear at compile-time. This avoids an IllegalArgumentException: wrong number of arguments exception.

public A1C0(final List<RoomStream>... occupancyLevels) {
    // constructor
}
public static void main(String[] args) throws Exception {
    final List<RoomStream> a = new ArrayList<RoomStream>();
    final List<RoomStream> b = new ArrayList<RoomStream>();
    final Class[] x = {List[].class};
    final List[] y = {a, b, d, e};
    final Object[] z = {y};
    final Constructor c = getClass().getConstructor(x);
    final Object o = c.newInstance(z);
    System.out.println(o);
}

Tags:

Thursday, November 12th, 2009 Code No Comments

Agile CTO