Thursday 20 March 2014

Reflection and Parameters Name

Reading the What's New? for the loooooooong awaited Java 8 release, I came across a new feature I hadn't heard about before: Method parameter reflection. Doing some search you'll findthat it's just getting the names of the parameters of a method. It seems like in order to enable this (by storing the parameter names in the .class), you'll have to compile your code with the -parameters option (notice that contrary to .Net, debug information in Java is also stored inside the .class file)

To store formal parameter names in a particular .class file, and thus enable the Reflection API to retrieve formal parameter names, compile the source file with the -parameters option to the javac compiler.

This seemed to bring some .Net echoes to my mind, so digging a bit in the recent past, I came up with this previous post. Retrieving the parameters names has always been possible as these names are stored in the Assembly metadata along with the rest of the method signature.

The method signature is part of metadata. Just to call the method it would be enough to know the binary offset of the method and its number and size of parameters. However, .NET stores the full signature: method name, return type, each parameter's exact type and name, any attributes on the method or parameters, etc.

So far JavaScript lacks a Reflection API per se, as Reflection is just an integral part of the language. That integral that we even can get the source of a function by calling its toString method. This way, we can get the names of the parameters with a simple regular expression.

No comments:

Post a Comment