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); }
Blogroll
Tech Startup
- "I don't want to be a product of my environment. I want my environment to be a product of me." - Frank Costigan, The Departed 1 week ago
- Actually said 'Good Morning' to his Mac when it it announced 'It's 8 o'clock'. Taking it to a whole new level... 1 week ago
- @auxbuss have found mockflow more helpful lately, partly as it's integrated with google apps. balsamiq has a more aesthetic UI though ;o) 1 week ago
- is reading up on #NoSQL and how best to store several '000 small read-only data tables. answers on a postcard please ;o) 1 week ago
- is now a big big fan of #git still getting there with the command line though, latest learning is git log --name-status 3 weeks ago
- @lleighton something i can help with? in reply to lleighton 3 weeks ago
- has broken the @Oracle database. that's a first ;o) 2010-07-17
- how to extend base or framework test classes from another module with #maven http://bit.ly/5hSvg 2010-06-24
- #java #developers. Interested in an #agile financial services #startup with secured funding? http://bit.ly/a0NNiX 2010-06-16
- looking into #oracle 11g UCP 2010-05-27
- More updates...
