Posted in Java

Named Parameters in Java 8

With Java 8 and the compiler flag: javac -parameters method parameter names are available via reflection.

Java 8

For example: the parameter names of the method hello:


public class Boundary {

    public void hello(String name, int age) {

    }
}

become accessible to the following code:


    public static void main(String[] args) {
        Method[] methods = Boundary.class.getMethods();
        for (Method method : methods) {
            System.out.print(method.getName() + "(");
            Parameter[] parameters = method.getParameters();
            for (Parameter parameter : parameters) {
                System.out.print(parameter.getType().getName() + " " + parameter.getName() + " ");
            }
            System.out.println(")");
        }
    }
}

Compilation with javac -parameters produces the following output:

hello(java.lang.String name int age )

Without the -parameters flag the names are not available:

hello(java.lang.String arg0 int arg1 )

@author: Adam Bien

Leave a comment