25 April 2014

Getting method parameter names in Java

It is a new feature in the api of Java8...

I remember that I needed to find such feature in pre java8 version, but I couldn't obtain it.. and when I rethink about it, I find that I have some design problem in my code!

All ways, Java8 contains some API that enables you get parameter names of the methods, provided that, you send some flag to the Javac compiler command line..

But the default is not to save the parameter for make the .class file compact and use less memory also for security reasons. see the java tutorial for more details.

The following is an example that show you the use of this api:

public static void main(String[] args) {

     Parameter[] params = Employee.class.getDeclaredMethods()[0]

     .map(param -> param.getName())
     .forEach(name -> System.out.println(name));

class Employee {
     public String getEmployeeNameById(int id) {
         return "Muhammad";

You need to compile this code by passing "-parameter" to the javac command to preserve the parameter names in the generated .class file.

BTW, the link of the java tutorial talks more about explicit vs implicit vs synthetic constructs in Java as well code examples.

hope find it hopeful!
Post a Comment