5

I need to get the parameter names of a method at runtime. Is there any way to achieve this?

I tried using LocalVariableTableParameterNameDiscoverer which is a Spring class. But it works only for classes and not the interfaces.

arshajii
  • 127,459
  • 24
  • 238
  • 287
Parag A
  • 443
  • 2
  • 8
  • 20
  • 2
    The only way this is really possible is through parsing a `.java` file. – Obicere Aug 12 '13 at 03:03
  • Here is something similar, might be all you need: http://stackoverflow.com/questions/2237803/can-i-obtain-method-parameter-name-using-java-reflection – Jlewis071 Aug 12 '13 at 03:46
  • As far as I know it will be possible in Java 8 reflection, otherwise you shall use bytcode manipulating libraries. – Amir Pashazadeh Aug 12 '13 at 04:47
  • This question is not a duplicate, his question is about getting the parameter names from a method defined in an interface and not a class. – eugen Apr 19 '15 at 20:18
  • The answer is: its not possible even when compiled with debug symbols, the parameter names are not in the byte code. http://www.jroller.com/eu/entry/using_asm_to_read_mathod – eugen Apr 19 '15 at 20:20
  • Are you sure you need the parameter names? – Kyle Strand Apr 19 '15 at 21:20
  • This question is definitely not duplicate. Still can't find a way to get parameter names from interfaces. Any help ? – Vaibhav Gupta Sep 30 '15 at 13:32
  • The Java8 solution described in [this answer](http://stackoverflow.com/a/20594685/466738) makes it a duplicate. Notice the need of compiling with `-parameters` flag. – Adam Michalik Jan 03 '17 at 09:17

1 Answers1

2

The only way to obtain the parameter names is to compile the source code using -g:vars options. This generates a LocalVariableTable attribute into the class file. This is generally removed for optimization.

For example: (taken from here)

public class Example {
   public int plus(int a){
     int b = 1;
     return a + b;
   }
 }

This will create a LocalVariableTable as follows

LocalVariableTable:

   Start  Length  Slot  Name     Signature
   0      6       0     this     LExample;
   0      6       1     a        I
   2      4       2     b        I

The LocalVariableTable can be read using any byte code instrumentation libraries like ASM or Javassist.

Santosh
  • 17,667
  • 4
  • 54
  • 79
  • Will this work for java Interfaces too? – Parag A Aug 12 '13 at 17:17
  • I have not tried myself but when compiled, interface translates to a .class file eventually, that why it should be consistent with .class of a Java Class file. – Santosh Aug 13 '13 at 12:58