0

Is there any way by which we can retrieve all the arguments/parameters of a method inside that method in a Map with key as parameter name and value as parameter value?

Say, I have a method with below signature:

public void do(String arg1, int arg2, String arg3, Double arg4, MyCustomObj arg5)

I want to achieve something like this:

public void do(String arg1, int arg2, String arg3, Double arg4, MyCustomObj arg5) {
Map<String, Object> argsMap = <what-goes-here>; logger.info("do ENTRY: "+argsMap); }

PS: I am not looking for a solution based on AOP. I want something that can be used within the method itself.

Update: This question is not about how to get values via Reflection. Please re-read before marking it as duplicate.

Mubin
  • 4,192
  • 3
  • 26
  • 45
  • 1
    You mean, the parameters to the _current_ method, from _inside_ that method? – tobias_k Jul 13 '15 at 10:16
  • Yes!! Somehow couldn't update the question. – Mubin Jul 13 '15 at 10:17
  • 2
    Take a look at: [How to get the value of a method argument via reflection in Java?](http://stackoverflow.com/questions/7230326/how-to-get-the-value-of-a-method-argument-via-reflection-in-java) – Tobías Jul 13 '15 at 10:23

2 Answers2

0

This seems to be a candidate of AOP and with spring where you could apply before advice, create your own map and print it.

SMA
  • 36,381
  • 8
  • 49
  • 73
  • 1
    You'd still have to create the map manually. – biziclop Jul 13 '15 at 10:22
  • Yes but it would be within advice and you just need to define it once like: `@Before(..) ..mymethod(..) { create map of args and send it to console and then proceed with normal routine`? – SMA Jul 13 '15 at 10:26
  • I may be wrong but I think the question is about how to "magically" obtain the parameters of a method in map form. – biziclop Jul 13 '15 at 10:30
  • Then that's worse! thanks @biziclop – SMA Jul 13 '15 at 10:39
0

You can use Varargs:

public void function(String... parameters) {
    for (int i = 0; i < parameters.length; i += 2) {
        System.out.println(parameters[i] + " " + parameters[i + 1]);
    }
}
chengpohi
  • 14,064
  • 1
  • 24
  • 42