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.

3
  • 1
    You mean, the parameters to the current method, from inside that method? Commented Jul 13, 2015 at 10:16
  • Yes!! Somehow couldn't update the question. Commented Jul 13, 2015 at 10:17
  • 2
    Take a look at: How to get the value of a method argument via reflection in Java? Commented Jul 13, 2015 at 10:23

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

You'd still have to create the map manually.
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?
I may be wrong but I think the question is about how to "magically" obtain the parameters of a method in map form.
Then that's worse! thanks @biziclop
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]);
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.