title: Call method with parameters through JSON in Java
body: <p>I am receiving JSON messages from an API (I have full control of the messages sent).
  The messages look like this :</p>
  
  <pre><code>{
   "function": "function_name",
   "arguments": { "arg1": "Value", "arg2": "Value"}
  }
  </code></pre>
  
  <p>I want to use reflection to call the right method with the right parameters and in the <strong>right</strong> order.
  The problem with that code is that the JSONObject conversion of the arguments doesn't keep the order of the parameters (which is normal given that JSON is, by definition, unordered).
  What I would need is some kind of mapping with the parameters name.</p>
  
  <p>Here is my Java code :</p>
  
  <pre><code>    String function_name = (String)json.get("function");
  
      ArrayList&lt;Class&gt; params = new ArrayList&lt;Class&gt;();
      ArrayList&lt;String&gt; values = new ArrayList&lt;String&gt;();
  
      JSONObject args = (JSONObject)json.get("arguments");
  
  
      if (args != null) {
          Set&lt;String&gt; keysargs = args.keySet();
          for (String key : keysargs) {
  
              params.add(args.get(key).getClass());
              values.add(args.get(key).toString());
          }
      }
  
      Method method;
      try {
        if (params.size() == 0) {
            method = this.getApplication().getClass().getMethod(function_name);
        }
        else {
            method = this.getApplication().getClass().getMethod(function_name, params.toArray(new Class[params.size()]));
        }
  
        try {
          method.invoke(this.getApplication(), values.toArray());
          } catch (IllegalAccessException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          } catch (IllegalArgumentException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          } catch (InvocationTargetException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
      } catch (SecurityException e) {
          e.printStackTrace();
      } catch (NoSuchMethodException e) {
          e.printStackTrace();
      }
  </code></pre>