Beispiel #1
0
  private void callMethodForParam(HttpServletRequest req, HttpServletResponse resp)
      throws Exception {
    String pinfo = req.getPathInfo();
    int pos = pinfo.indexOf('.');
    String cname = pinfo.substring(1, pos).replace('/', '.');
    String mname = pinfo.substring(pos + 1);

    int argc = 0;
    while (req.getParameter("a" + argc) != null) argc++;

    Class clazz = Class.forName(cname);
    Method method = null;
    Method[] methods = clazz.getMethods();
    for (int i = 0; i < methods.length; i++) {
      if (methods[i].getParameterTypes().length == argc && mname.equals(methods[i].getName())) {
        method = methods[i];
      }
    }
    if (method == null) {
      throw new RuntimeException("Not found method " + mname + "(" + argc + "args)");
    }

    Object[] args = new Object[argc];
    Class[] types = method.getParameterTypes();
    if (types != null) {
      for (int i = 0; i < types.length; i++) {
        args[i] = toArg(types[i], req.getParameter("a" + i));
      }
    }

    Object result = method.invoke(null, args);

    resp.setContentType(MIME_JSON);
    OutputStream out = resp.getOutputStream();
    out.write("{\"result\":".getBytes("UTF-8"));
    new JSONSerializer().serialize(result, out);
    out.write("}".getBytes("UTF-8"));
    out.flush();
  }