Exemplo n.º 1
0
  /**
   * Copy from the copy method in StructUtil. Did not want to drag that code in. maybe this actually
   * should go to struct.
   *
   * @param from
   * @param to
   * @param excludes
   * @return
   * @throws Exception
   */
  public static <T extends struct> T xcopy(struct from, T to, String... excludes) throws Exception {
    Arrays.sort(excludes);
    for (Field f : from.fields()) {
      if (Arrays.binarySearch(excludes, f.getName()) >= 0) continue;

      Object o = f.get(from);
      if (o == null) continue;

      Field tof = to.getField(f.getName());
      if (tof != null)
        try {
          tof.set(to, Converter.cnv(tof.getGenericType(), o));
        } catch (Exception e) {
          System.out.println(
              "Failed to convert "
                  + f.getName()
                  + " from "
                  + from.getClass()
                  + " to "
                  + to.getClass()
                  + " value "
                  + o
                  + " exception "
                  + e);
        }
    }

    return to;
  }
Exemplo n.º 2
0
 @SuppressWarnings({"unchecked", "rawtypes"})
 public static Object invoke(Object target, Method method, boolean strict, Object... args) {
   try {
     Object[] params;
     Class<?>[] paramTypes = method.getParameterTypes();
     if (paramTypes.length == 0) {
       params = null;
     } else if (args.length == paramTypes.length) {
       // map one to one
       if (strict) {
         params = args;
       } else {
         params = new Object[paramTypes.length];
         for (int i = 0; i < paramTypes.length; i++) {
           Object arg = args[i];
           if (arg == null) params[i] = null;
           else {
             Converter converter =
                 ConverterManager.getInstance().createConverter(arg.getClass(), paramTypes[i]);
             params[i] = converter.convert(arg);
           }
         }
       }
     } else {
       // map varargs
       params = new Object[paramTypes.length];
       for (int i = 0; i < paramTypes.length - 1; i++)
         params[i] = (strict ? args[i] : AnyConverter.convert(args[i], paramTypes[i]));
       Class<?> varargsComponentType = paramTypes[paramTypes.length - 1].getComponentType();
       Object varargs =
           Array.newInstance(varargsComponentType, args.length - paramTypes.length + 1);
       for (int i = 0; i < args.length - paramTypes.length + 1; i++) {
         Object param = args[paramTypes.length - 1 + i];
         if (strict) param = AnyConverter.convert(param, varargsComponentType);
         Array.set(varargs, i, param);
       }
       params[params.length - 1] = varargs;
     }
     return method.invoke(target, params);
   } catch (IllegalAccessException e) {
     throw ExceptionMapper.configurationException(e, method);
   } catch (InvocationTargetException e) {
     throw ExceptionMapper.configurationException(e, method);
   }
 }