Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

java-8

I am using Java 8. In Java 8 there is a method name as get parameter but it gives the output like arg0, arg1. 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.

like image 998
shubham pandey Avatar asked Sep 10 '25 01:09

shubham pandey


1 Answers

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)
{
    System.out.println(parameter.getName());
}

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.

like image 59
Eng.Fouad Avatar answered Sep 13 '25 16:09

Eng.Fouad