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

Events
Aug 29 - Sep 1
Boston, MA
HPE Big Data Conference 2016
Attend HPE’s Big Data Conference on August 29 - September 1, 2016 to learn from peers in every industry and hear from Big Data experts and thought lea...
Read more
Sep 13-16
National Harbor, MD
HPE Protect 2016
Protect 2016 is our annual conference on September 13 - 16, 2016, and is the place to meet the world’s top information security talent, discuss new pr...
Read more
View all