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?

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
syraz37
  • 756
  • 2
  • 6
  • 11
  • i don't think that making something like `dynamic methods` or similar to javascript `prototype` is possible in java. – itwasntme Aug 18 '15 at 19:45
  • 1
    My question is why would you do that? `jm.put("key","value")` is already very simple in writing – itwasntme Aug 18 '15 at 19:56
  • U also can mess up a little bit and make something like this: http://pastebin.com/MtggQ9Ec but for me it just looks worse than standard `jm.put("key","val");` – itwasntme Aug 18 '15 at 20:17

3 Answers3

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)
Gergely Bacso
  • 14,243
  • 2
  • 44
  • 64
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);
}
nLee
  • 1,320
  • 2
  • 10
  • 21
  • 2
    whole implementation would be case dependent and he would need to write method for every key he wants to include to JSON object – itwasntme Aug 18 '15 at 19:47
  • @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. – Andreas Aug 18 '15 at 19:58
  • 1
    @nLee Given his example, the `setId` method should take an `int`. – Andreas Aug 18 '15 at 20:01
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.

Andreas
  • 154,647
  • 11
  • 152
  • 247