示例#1
0
  public static <T extends Factory> T objectFromJson(JsonObject json, T prototype)
      throws ParseException {
    T object = (T) prototype.create();

    Method[] methods = object.getClass().getMethods();

    for (final Method method : methods) {
      if (method.getName().startsWith("set") && method.getParameterTypes().length == 1) {

        final String name = Introspector.decapitalize(method.getName().substring(3));
        Class<?> parameterType = method.getParameterTypes()[0];

        if (json.containsKey(name))
          try {
            if (parameterType.equals(boolean.class)) {
              method.invoke(object, json.getBoolean(name));
            } else if (parameterType.equals(int.class)) {
              method.invoke(object, json.getJsonNumber(name).intValue());
            } else if (parameterType.equals(long.class)) {
              if (json.get(name).getValueType() == JsonValue.ValueType.NUMBER) {
                method.invoke(object, json.getJsonNumber(name).longValue());
              }
            } else if (parameterType.equals(double.class)) {
              method.invoke(object, json.getJsonNumber(name).doubleValue());
            } else if (parameterType.equals(String.class)) {
              method.invoke(object, json.getString(name));
            } else if (parameterType.equals(Date.class)) {
              method.invoke(object, dateFormat.parse(json.getString(name)));
            } else if (parameterType.equals(Map.class)) {
              method.invoke(object, MiscFormatter.fromJson(json.getJsonObject(name)));
            }
          } catch (IllegalAccessException | InvocationTargetException error) {
          }
      }
    }

    return object;
  }