0

I have a class

class JsonMap extends HashMap<String, Object> {}

I initialized an object like this

JsonMap jm = new JsonMap();

I am inserting data into it like this

jm.put("id", 4);
jm.put("message", "Hello");

but i want to do something easy like this with same effect.

jm.setId(4);
jm.setMessage("Hello");

Is this possibe without having to write methods setId and setMessage in JsonMap class?

function name is dynamic: first part is always 'set' and second part is dynamic value. this will go as key inside HashMap.

Can anyone show me how to achieve this, if it's possible?

3
  • i don't think that making something like dynamic methods or similar to javascript prototype is possible in java. Commented Aug 18, 2015 at 19:45
  • 1
    My question is why would you do that? jm.put("key","value") is already very simple in writing Commented Aug 18, 2015 at 19:56
  • U also can mess up a little bit and make something like this: pastebin.com/MtggQ9Ec but for me it just looks worse than standard jm.put("key","val"); Commented Aug 18, 2015 at 20:17

3 Answers 3

1

What you are looking for is not possible as the language does not support this kind of feature, so at least you can stop looking for a built-in language feature. The alternative options you may want to look at:

  • professional JSON serializers (like Jackson)
  • JSONtoPOJO converters (many of these are available online)
Sign up to request clarification or add additional context in comments.

Comments

0

Java is a strongly typed language, not a scripting language, so no, it is not possible without having to write methods setId and setMessage in the JsonMap class.

Comments

0

you would need to write methods to do this for you

public void setId(int id) {
    jm.put("id", id);
}

public void setMessage(String message) {
    jm.put("message", message);
}

3 Comments

whole implementation would be case dependent and he would need to write method for every key he wants to include to JSON object
@syraz37 Java is a strongly typed language, not a scripting language. jm.setId(4) requires that the setId(int) method is defined in the class.
@nLee Given his example, the setId method should take an int.

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.