Ryan Harrison
My blog, portfolio and technology related ramblings
Java - Write code indirectly using reflection
05 Sep 2013
In a recent post I showed how it is possible to write all your C# code indirectly through reflection. Here is the same example in Java. The process itself is very much the same - retrieve meta information about the classes/methods we are interested in and then invoke them passing in the object it would normally be called from. The classes themselves are all very similar through C# to Java. Type becomes Class, MethodInfo becomes Method etc.
A more interesting difference is how the Java version uses variable length parameters in the .invoke calls on Method objects as a way of passing parameters to the particular method. In the C# version you have to explicitly pass a Type or object array. I think the Java version is slightly more user friendly in that quite small regard even though the actual parameter itself is an array in both circumstances.
Its also interesting to see just how many exceptions the Java version can throw in the process. Because they are all checked you are forced to deal with them whereas C# does not have this feature. Its probably likely then that you would have to catch a more generic exception in the C# version.
Here is the code for the Java version. The result is the same as the C# version.