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); }
Agile CTO
- tech_startup: Puppet certificate issues http://t.co/oM6y53rx 4 days ago
- have invented a new UNIX tool for cutting the grass: sudo chmown aeells:aeells squid.conf.bkp sudo: chmown: command not found 5 days ago
- I support #wikipediablackout Show your support here http://t.co/UFN8O0gk 2 weeks ago
- reasonable man adapts himself to world; unreasonable man tries to adapt world to himself; => all progress depends on unreasonable man. 3 weeks ago
- @blinkdesign we could do that too!!!!? ;o) in reply to blinkdesign 3 weeks ago
- @blinkdesign we could do something similar on our tech blog maybe... in reply to blinkdesign 3 weeks ago
- ".....in all things, the supreme excellence is simplicity." Henry Wadsworth Longfellow 3 weeks ago
- good day bootstrapping #tomcat #memcached to #aws server via #puppet - looking forward to provisioning entire production replica in minutes! 3 weeks ago
- great (practical) example of how to do #continousdeployment and branching within teams http://t.co/ceeyvD0h courtesy @chacon @domfarr 2012-01-05
- hi @ruv, mind if i ask how you came by that statistic? cheers! in reply to ruv 2012-01-02
- More updates...


