1

Suppose I have a few variables:

public void foo() {
    String name = "Bob";
    String gender = "Male";
    Integer age = 6;
    String address = "some address";
}

How can I turn them into a Map<String, Object> like

Map<String, Object> map = new HashMap<>();
map.put("name", name);
map.put("gender", gender);
map.put("age", age);
map.put("address", address);

other than manually inserting them into the map. Can this be done using Reflection?

4
  • 1
    What do you really need? A map or an String in that format? Commented Mar 17, 2016 at 18:52
  • You're trying to write a JSon? Commented Mar 17, 2016 at 18:58
  • Just edited my question, it has nothing to do with Json, I just need a map :) Commented Mar 17, 2016 at 22:37
  • @WoLfPwNeR You just can't do that. name, gender etc are local variables, and reflection can't be used for local variables. If they were fields it would be different. Commented Mar 18, 2016 at 11:32

4 Answers 4

4

No, you have to manually put them into a map. It is not possible to use reflection to find the names or values of local variables.

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

Comments

3

Dont re invent the wheel use Json libraries and parse your objects

Example (using Gson...):

public class GenericTypeData {
    private String name = "Bob";
    private String gender = "Male";
    private int age = 6;
    private String address = "some address";
    
    public GenericTypeData( ) {
        this.name = "Bob";
        this.gender = "Male";
        this.age = 6;
        this.address = "some address";
    }

    public static void main(String[] args) {
        System.out.println(new Gson().ToJson(this, GenericTypeData.class));
    }

}

you will get a json like

{
    "name": "Bob",
    "gender": "Male",
    "age": 6,
    "address": "some address", 
}

Comments

0

If your variables are fixed for a class to convert into map then you can convert them into a json.

You can first prepare your object containing variables and then use toJson() method to convert it into the format as you specified in your question.

This link may help for usage of toJson() method from google gson library.

Comments

0

If you are interested in String, you can use the method ReflectionToStringBuilder.toString(Object, ToStringStyle) from Apache Commons Lang. Using JSON_STYLE.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.