Java Dynamic Function Call

444 Views Asked by At

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

There are 3 best solutions below

3
On

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);
}
0
On

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.

0
On

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)