shubham pandey shubham pandey - 1 year ago 114
Java Question

How can I get the parameter name in java at run time

I am using Java 8. In Java 8 there is a method name as get parameter but it gives the output like

. However I want the exact parameter name. Can anybody tell me how to achieve it? I have seen some response like we can use paranamer. But I couldn't find the solution. I am trying to build an automation framework so I have this requirement.

for example if my function is

public void Login(String sUserName, String sPassword)

So in a different class file I want the output as sUserName.

Answer Source

Starting from Java 8, you can use Reflection API to retrieve parameters names:

Method someMethod = Main.class.getDeclaredMethod("someMethod");
Parameter[] parameters = someMethod.getParameters();
for(Parameter parameter : parameters)

Also, see JavaDoc of Parameter#getName():

Returns the name of the parameter. If the parameter's name is present, then this method returns the name provided by the class file. Otherwise, this method synthesizes a name of the form argN, where N is the index of the parameter in the descriptor of the method which declares the parameter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download