示例#1
0
 @SuppressWarnings("boxing") // boxing is deliberate here
 @Test
 public void testIsInstance() throws SecurityException, NoSuchFieldException {
   final Type intComparableType = getClass().getField("intComparable").getGenericType();
   final Type uriComparableType = getClass().getField("uriComparable").getGenericType();
   intComparable = 1;
   Assert.assertTrue(TypeUtils.isInstance(1, intComparableType));
   // uriComparable = 1;
   Assert.assertFalse(TypeUtils.isInstance(1, uriComparableType));
 }
示例#2
0
  public static <SRC, DEST> DEST convert(SRC sourceObject, Class<DEST> toClass)
      throws ConversionException {

    if (sourceObject == null) return null;

    try {
      DEST destinationObject = toClass.newInstance();
      List<Field> fields = getAllFields(sourceObject.getClass());

      for (Field field : fields) {
        Method sourceGetter = getGetter(sourceObject.getClass(), field);
        Method destinationSetter = getSetter(toClass, field);

        if (sourceGetter == null) continue;

        try {
          Object toSet = sourceGetter.invoke(sourceObject);
          if (destinationSetter != null && toSet != null) { // if setting object or primitive type
            Class<?> parameterType = destinationSetter.getParameterTypes()[0];
            if (TypeUtils.isInstance(toSet, parameterType)) {
              // if toSet is castable to parameter type, set it directly
              destinationSetter.invoke(destinationObject, toSet);
            } else if (toSet != null) {
              // if toSet is an unknown object, translate it via recursion
              destinationSetter.invoke(
                  destinationObject, convert(toSet, parameterType)); // recursion
            }
          }
        } catch (InvocationTargetException e) {
          e.printStackTrace(); // don't throw to continue in mapping other fields
        }
      }
      return destinationObject;
    } catch (IllegalAccessException | IllegalArgumentException | InstantiationException e) {
      e.printStackTrace();
      throw new ConversionException(e);
    }
  }