Skip to Content

Get parameter names in Java 8

Before Java 8, it was very difficult to get parameter names at runtime. For example, Spring’s @PathVariable annotation needs you to either repeat the name of the annotated parameter like this:

public String findOwner(@PathVariable("ownerId") String ownerId) {
}

Or, make sure the code is compiled with debug information and let Spring do some black magic with this information. You can then remove some duplication in your code:

public String findOwner(@PathVariable String ownerId) {
}

With Java 8, parameter names can be retrieved at runtime with this code:

String name = String.class.getMethod("substring", int.class).getParameters()[0].getName()
System.out.println(name);

Well it turns out that parameters names are still not activated by default. You have to compile your code with -parameters javac command line option.

At least, it removes some dark magic out of the process.

comments powered by Disqus