Simplified Array Syntax
April 4th, 2008
Sometimes, when working with Java 5/6, you still have to call methods from pre-Java 5 libraries. For instance, many of our DAOs are littered with code similar to this:
jdbcTemplate.query(sql,
new Object[]{ customerId, customerName },
new int[]{Types.INTEGER, Types.VARCHAR},
... );
I don’t like the new Object[] { … }, So today I wrote a static method:
public static <T> T[] array(T... t) {
return t;
}
And another for primitive ints:
public static int[] intArray(int... i) {
return i;
}
Thus, I can now write the original code like this:
jdbcTemplate.query(sql,
array(customerId, customerName),
intArray(INTEGER, VARCHAR),
... );
I have to say that static imports and varargs are among my favorite Java 5 syntax features. Now if only I didn’t have to have special methods to handle arrays of primitives.