Software Developers
Showing results for 
Search instead for 
Do you mean 

Reading a Java Method's Parameter Names

amirkibbar on ‎05-22-2013 10:46 PM

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]

 

0 Kudos
About the Author

amirkibbar

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.
Events
Aug 29 - Sep 1
Boston, MA
HPE Big Data Conference 2016
Attend HPE’s Big Data Conference to learn from peers in every industry and hear from Big Data experts and thought leaders in an exciting, energy fille...
Read more
Sep 13-16
National Harbor, MD
HPE Protect 2016
Protect 2016 is our annual conference and is the place to meet the world’s top information security talent, discuss new products and share information...
Read more
View all