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);

WAIT! It prints arg0, not beginIndex !!!

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.

Why is it not activated by default. That’s beyond me.

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

One thought on “Get parameter names in Java 8”

  1. If you own the API and use annotations, you can access parameter names at compilation time and write them in an resource file along with the classes (foo.Bar -> foo.Bar.data) with an annotation processor. This works since Java 1.6

Comments are closed.