0

I would like to get the name of each parameter and value coming to my method in java. I searched about it but I could not find something to help me. Can you show me a solution. I have a method as below

public HashMap<String, Object> putallinMap(Object...pars){
     HashMap<String, Object> map = new HashMap<String, Object>();
     map.put(pars[0].{name}, pars[0].{value});
     return map;
}

This is How I call the method above.

String str1 = "Hello world!";
int myint = 55;
double myDouble = 11.5;
...// there can be other primitive types, long, short, Double etc.

HashMap<String, Object> map attrInMap = putallinMap(str1, myint, myDouble);

Sow What I expect to have a hasmap like below.

{"str1":"Hello world!", "myint" : 55, "myDouble": 11.5}
gabby
  • 629
  • 2
  • 11
  • 34
  • You can't get names but only values. – StanislavL Feb 27 '15 at 13:49
  • It depends. If your variables are declared at the class level, you can get their names. Otherwise, if they are local, I don't think it's possible to do so. – TNT Feb 27 '15 at 13:55

1 Answers1

0

you can't get the variable name, since its only a reference to a class. I suggest you simply get the Object Type instead. in term of getting the value just add the object

Something like this

public HashMap<String, Object> putallinMap(Object...pars){
     HashMap<String, Object> map = new HashMap<String, Object>();
     map.put(pars[0].getClass(), pars[0]);
     return map;
}

and based on ur input the output will be as follows:

{"String":"Hello world!", "Integer" : 55, "Double": 11.5}

NOTE :

for further info I found this nice stackoverflow question:

Java Reflection: How to get the name of a variable?

Community
  • 1
  • 1
nafas
  • 5,283
  • 3
  • 29
  • 57
  • Thanks for your answer. But my requirement force me to have name of attribute instead of class name. I remember I have seen something like that in play framework source code. They were keeping request params to next scope by doing something like that. But ı could not find it now.. – gabby Feb 27 '15 at 13:59
  • @gabby well I suppose that is a java problem, you are probably using a wrong programming language to achieve your task. – nafas Feb 27 '15 at 14:31
  • I can not get the play framework repo to my workspace now. When I do I will share from here. Im sure Im using Java :) – gabby Feb 27 '15 at 14:42
  • @gabby as far as I know, play uses scala also, maybe its some scala library that allows u to do it – nafas Feb 27 '15 at 14:47
  • Sorry not to tell version. what i checked last time was play 1.2.5 – gabby Feb 27 '15 at 14:52