Reading a Java Method's Parameter Names

Sometimes there is a benefit in knowing the parameter names of a method at runtime without doing anything special about it, i.e. without adding a custom annotation.

This can easily be done with the help of Paranamer. This (very small) library provides 3 methods to resolve the method parameters names:

  1. Reading the debug information from the bytecode - this requires that the code will be compiled with debug information. Fortunately most products compile with debug information and never release the product without it.
  2. Reading information added with a post-compile bytecode instrumentation process
  3. Reading information from annotations

 

Since most modern frameworks (e.g. Spring) use debug information and since most products don't bother with "production" builds without this debug information, then I think that that's the preferred way to go.

 

Here's how it's done:

import com.thoughtworks.paranamer.BytecodeReadingParanamer;
import com.thoughtworks.paranamer.CachingParanamer;
import com.thoughtworks.paranamer.Paranamer;
import org.junit.Test;

import java.util.Arrays;

public class ParanamerTest {
    @Test
    public void foo() throws NoSuchMethodException {
        Paranamer p = new CachingParanamer(new BytecodeReadingParanamer());
        System.out.println(Arrays.toString(p.lookupParameterNames(getClass().getDeclaredMethod("bar", String.class, Boolean.class))));
    }

    private void bar(String str1, Boolean flag2) {
    }
}

 

And the result of running the above code is:

[str1, flag2]

 

Labels: Java
Leave a Comment

We encourage you to share your comments on this post. Comments are moderated and will be reviewed
and posted as promptly as possible during regular business hours

To ensure your comment is published, be sure to follow the Community Guidelines.

Be sure to enter a unique name. You can't reuse a name that's already in use.
Be sure to enter a unique email address. You can't reuse an email address that's already in use.
Type the characters you see in the picture above.Type the words you hear.
Search
Showing results for 
Search instead for 
Do you mean 
About the Author
Featured


Follow Us
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation.