Пример #1
0
  static Class<?> getTypeClass(Type type) {

    if (type instanceof Class<?>) {
      return (Class<?>) type;
    }
    if (type instanceof ParameterizedType) {
      ParameterizedType pt = (ParameterizedType) type;
      Class<?> c = (Class<?>) pt.getRawType();
      if (ValuedEnum.class.isAssignableFrom(c)) {
        Type[] types = pt.getActualTypeArguments();
        if (types == null || types.length != 1) {
          c = int.class;
        } else {
          c = getTypeClass(pt.getActualTypeArguments()[0]);
        }
      }
      return c;
    }
    if (type instanceof GenericArrayType) {
      if (Object.class.isAssignableFrom(
          getTypeClass(((GenericArrayType) type).getGenericComponentType()))) {
        return Object[].class;
      }
    }
    throw new UnsupportedOperationException("Unknown type type : " + type.getClass().getName());
  }
 @SuppressWarnings("unchecked")
 private void apply(Object mock) {
   for (Refinement refinement : refinements) {
     ParameterizedType generic =
         (ParameterizedType) refinement.getClass().getGenericInterfaces()[0];
     Class<?> restrained =
         generic.getActualTypeArguments()[0] instanceof ParameterizedType
             ? (Class<?>) ((ParameterizedType) generic.getActualTypeArguments()[0]).getRawType()
             : (Class<?>) generic.getActualTypeArguments()[0];
     if (restrained.isInstance(mock)) {
       refinement.apply(mock);
     }
   }
 }
 private Object replace(Class<?> type, ApplicableGenerator generator, boolean alternative) {
   for (Creator<?> creator : creators) {
     ParameterizedType generic =
         (ParameterizedType) creator.getClass().getGenericInterfaces()[0];
     Class<?> restrained =
         generic.getActualTypeArguments()[0] instanceof ParameterizedType
             ? (Class<?>) ((ParameterizedType) generic.getActualTypeArguments()[0]).getRawType()
             : (Class<?>) generic.getActualTypeArguments()[0];
     if (type.isAssignableFrom(restrained)) {
       return creator.create();
     }
   }
   return generator.generate(type, alternative);
 }
 private Object generate(Class<?> type, boolean alternative) {
   for (Generator<?> generator : generators) {
     ParameterizedType generic =
         (ParameterizedType) generator.getClass().getGenericInterfaces()[0];
     Class<?> restrained =
         generic.getActualTypeArguments()[0] instanceof ParameterizedType
             ? (Class<?>) ((ParameterizedType) generic.getActualTypeArguments()[0]).getRawType()
             : (Class<?>) generic.getActualTypeArguments()[0];
     if (type.isAssignableFrom(restrained)) {
       type = generator.generate();
     }
   }
   return type == String.class ? alternative ? OTHER_STRING : DEFAULT_STRING : mock(type);
 }
Пример #5
0
  /**
   * @param type - something like List&lt;T>, List&lt;T extends Number>
   * @param containingType - the shallowest type in the hierarchy where type is defined.
   * @return the passed type if nothing to resolve or a copy of the type with the type arguments
   *     resolved.
   */
  private static ParameterizedType resolve(ParameterizedType type, Type containingType) {
    // Use a copy because we're going to modify it.
    final Type[] types = type.getActualTypeArguments().clone();

    boolean modified = resolve(types, containingType);
    return modified ? create(type.getRawType(), type.getOwnerType(), types) : type;
  }
Пример #6
0
 static Class<?> resultType(Method finderMethod) {
   checkArgument(finderMethod.getReturnType() == Iterator.class);
   Type t = finderMethod.getGenericReturnType();
   ParameterizedType pt = (ParameterizedType) t;
   Type r = pt.getActualTypeArguments()[0];
   return (Class<?>) r;
 }
Пример #7
0
 private static int checkParameterizedType(
     String subroutineName,
     ParameterizedType expectedType,
     ArgumentsList arguments,
     List<LispObject> args,
     int argsCounter,
     int i) {
   Type rawType = expectedType.getRawType();
   Type expectedTypeArguments = expectedType.getActualTypeArguments()[0];
   try {
     if (((Class) rawType).isInstance(args.get(argsCounter))) {
       Type actualTypeArguments =
           ((ParameterizedType) (Type) args.get(argsCounter).getClass())
               .getActualTypeArguments()[0];
       if (!expectedTypeArguments.equals(actualTypeArguments)) {
         throw new WrongTypeArgumentException(
             ((Class) rawType).getSimpleName()
                 + "<"
                 + ((Class) expectedTypeArguments).getSimpleName()
                 + ">",
             args.get(argsCounter));
       }
       arguments.setValue(i, args.get(argsCounter));
       return argsCounter + 1;
     } else {
       if (arguments.isOptional(i)) return -1;
       throw new WrongTypeArgumentException(expectedType.toString(), args.get(argsCounter));
     }
   } catch (IndexOutOfBoundsException e) {
     if (arguments.isOptional(i)) return -1;
     throw new WrongNumberOfArgumentsException(subroutineName, i);
   }
 }
Пример #8
0
 @Nullable
 private static TypeWrapper wrap(Type type) {
   if (type == null) {
     return null;
   } else if (type instanceof Class) {
     return new ClassTypeWrapper((Class<?>) type);
   } else if (type instanceof ParameterizedType) {
     ParameterizedType parameterizedType = (ParameterizedType) type;
     return new ParameterizedTypeWrapper(
         toWrappers(parameterizedType.getActualTypeArguments()),
         (ClassTypeWrapper) wrap(parameterizedType.getRawType()),
         wrap(parameterizedType.getOwnerType()));
   } else if (type instanceof WildcardType) {
     WildcardType wildcardType = (WildcardType) type;
     return new WildcardTypeWrapper(
         toWrappers(wildcardType.getUpperBounds()),
         toWrappers(wildcardType.getLowerBounds()),
         type.hashCode());
   } else if (type instanceof TypeVariable) {
     TypeVariable<?> typeVariable = (TypeVariable<?>) type;
     return new TypeVariableTypeWrapper(
         typeVariable.getName(), toWrappers(typeVariable.getBounds()), type.hashCode());
   } else if (type instanceof GenericArrayType) {
     GenericArrayType genericArrayType = (GenericArrayType) type;
     return new GenericArrayTypeWrapper(
         wrap(genericArrayType.getGenericComponentType()), type.hashCode());
   } else {
     throw new IllegalArgumentException("cannot wrap type of type " + type.getClass());
   }
 }
 private Type getElementType(ParameterizedType type, int index) {
   Type elementType = type.getActualTypeArguments()[index];
   if (elementType instanceof WildcardType) {
     WildcardType wildcardType = (WildcardType) elementType;
     return wildcardType.getUpperBounds()[0];
   }
   return elementType;
 }
Пример #10
0
 /**
  * Returns the generic type information of an attribute.
  *
  * @param field the field representation of the attribute.
  * @return an array of types that are used to parameterize the attribute.
  */
 public static Class<?>[] getGenericTypes(Field field) {
   Type genericFieldType = field.getGenericType();
   if (!(genericFieldType instanceof ParameterizedType)) return null; // type is not generic
   ParameterizedType pType = (ParameterizedType) genericFieldType;
   Type[] args = pType.getActualTypeArguments();
   Class<?>[] types = new Class[args.length];
   System.arraycopy(args, 0, types, 0, args.length);
   return types;
 }
Пример #11
0
  @Test
  public void get_generic_type_of_a_field() throws Exception {
    Field field = Dummy.class.getDeclaredField("stringListField");
    ParameterizedType type = (ParameterizedType) field.getGenericType();

    assertEquals(List.class, type.getRawType());
    assertArrayEquals(new Type[] {String.class}, type.getActualTypeArguments());
    assertEquals(null, type.getOwnerType());
  }
  public static <T> Class<T> tellMeTheTypeOfThisThing() throws NoSuchMethodException {
    Method method =
        InferGenericTypeForAStaticMethodTest.class.getDeclaredMethod(
            "tellMeTheTypeOfThisThing", null);

    ParameterizedType type = (ParameterizedType) method.getGenericReturnType();
    TypeVariableImpl typeImpl = (TypeVariableImpl) type.getActualTypeArguments()[0];
    System.out.println(typeImpl);
    return null;
  }
Пример #13
0
  @Test
  public void get_generic_type_of_interface_method_parameters() throws Exception {
    Method method = Interface.class.getDeclaredMethod("stringListMethod", List.class);
    Type[] types = method.getGenericParameterTypes();
    ParameterizedType type = (ParameterizedType) types[0];

    assertEquals(List.class, type.getRawType());
    assertArrayEquals(new Type[] {String.class}, type.getActualTypeArguments());
    assertEquals(null, type.getOwnerType());
  }
Пример #14
0
 private void visitType(java.lang.reflect.Type type, StringBuilder builder) {
   if (type instanceof Class) {
     Class<?> cl = (Class<?>) type;
     if (cl.isPrimitive()) {
       builder.append(Type.getType(cl).getDescriptor());
     } else {
       if (cl.isArray()) {
         builder.append(cl.getName().replace('.', '/'));
       } else {
         builder.append('L');
         builder.append(cl.getName().replace('.', '/'));
         builder.append(';');
       }
     }
   } else if (type instanceof ParameterizedType) {
     ParameterizedType parameterizedType = (ParameterizedType) type;
     visitNested(parameterizedType.getRawType(), builder);
     builder.append('<');
     for (java.lang.reflect.Type param : parameterizedType.getActualTypeArguments()) {
       visitType(param, builder);
     }
     builder.append(">;");
   } else if (type instanceof WildcardType) {
     WildcardType wildcardType = (WildcardType) type;
     if (wildcardType.getUpperBounds().length == 1
         && wildcardType.getUpperBounds()[0].equals(Object.class)) {
       if (wildcardType.getLowerBounds().length == 0) {
         builder.append('*');
         return;
       }
     } else {
       for (java.lang.reflect.Type upperType : wildcardType.getUpperBounds()) {
         builder.append('+');
         visitType(upperType, builder);
       }
     }
     for (java.lang.reflect.Type lowerType : wildcardType.getLowerBounds()) {
       builder.append('-');
       visitType(lowerType, builder);
     }
   } else if (type instanceof TypeVariable) {
     TypeVariable<?> typeVar = (TypeVariable) type;
     builder.append('T');
     builder.append(typeVar.getName());
     builder.append(';');
   } else if (type instanceof GenericArrayType) {
     GenericArrayType arrayType = (GenericArrayType) type;
     builder.append('[');
     visitType(arrayType.getGenericComponentType(), builder);
   } else {
     throw new IllegalArgumentException(
         String.format("Cannot generate signature for %s.", type));
   }
 }
Пример #15
0
  /**
   * Gets the type of a parameterized List
   *
   * @param scope
   * @return
   */
  public Class getParameterizedListType(Scope scope) {
    Type returnType = method.getGenericReturnType();
    ParameterizedType type = (ParameterizedType) returnType;
    Type[] typeArguments = type.getActualTypeArguments();
    Class typeArgClass = (Class) typeArguments[0];
    // System.out.println("typeArgClass = " + typeArgClass);
    return typeArgClass;

    /*
     * Class rtnType = method.getReturnType(); TypeVariable[] typeParam =
     * rtnType.getTypeParameters(); Class listType = typeParam[0].getClass();
     * return ClassUtil.getObjectClass(listType);
     */
  }
Пример #16
0
  private Class<?> resolveReturnType(Method me) {
    Type returnType = me.getGenericReturnType();

    if (returnType instanceof ParameterizedType) {
      ParameterizedType type = (ParameterizedType) returnType;
      Type[] typeArguments = type.getActualTypeArguments();
      for (Type typeArgument : typeArguments) {
        if (typeArgument instanceof Class<?>) {
          return (Class<?>) typeArgument;
        }
      }
      return null;
    }
    return (Class<?>) returnType;
  }
 private ReferenceTypeUsage toReferenceTypeUsage(Class<?> clazz, Type type) {
   TypeDefinition typeDefinition = new ReflectionBasedTypeDefinition(clazz);
   ReferenceTypeUsage referenceTypeUsage = new ReferenceTypeUsage(typeDefinition);
   if (type instanceof ParameterizedType) {
     ParameterizedType parameterizedType = (ParameterizedType) type;
     for (int tp = 0; tp < clazz.getTypeParameters().length; tp++) {
       TypeVariable<? extends Class<?>> typeVariable = clazz.getTypeParameters()[tp];
       Type parameterType = parameterizedType.getActualTypeArguments()[tp];
       referenceTypeUsage
           .getTypeParameterValues()
           .add(typeVariable.getName(), toTypeUsage(parameterType));
     }
   }
   return referenceTypeUsage;
 }
Пример #18
0
 public static <C, I> Type[] getGenericInterfaceParams(
     Class<C> checkedClass, Class<I> searchedInterface) {
   for (Type type : checkedClass.getGenericInterfaces()) {
     ParameterizedType pt = (ParameterizedType) type;
     if (searchedInterface.equals(pt.getRawType())) {
       ParameterizedType pType = ((ParameterizedType) type);
       return pType.getActualTypeArguments();
     }
   }
   if (!Object.class.equals(checkedClass.getSuperclass()))
     return getGenericInterfaceParams(checkedClass.getSuperclass(), searchedInterface);
   throw new ConfigurationError(
       checkedClass
           + " does not implement interface with generic parameters: "
           + searchedInterface);
 }
Пример #19
0
 public boolean isAssignableTo(Type<?> superType) {
   if (this == superType) return true;
   if (superType == Types.ANY) return true;
   if (superType instanceof RuntimeType<?>) {
     RuntimeType<?> rt = (RuntimeType<?>) superType;
     if (rt.javaClass.isAssignableFrom(javaClass)) {
       return true;
     }
   }
   if (superType instanceof ParameterizedType) {
     ParameterizedType<?> pt = (ParameterizedType<?>) superType;
     if (pt.getRawType().isAssignableFrom(pt.getActualTypeArguments(), this, null)) {
       return true;
     }
   }
   return false;
 }
Пример #20
0
  public static Class<?> getActualType(Type genericType, final int pos) {

    if (genericType == null) return null;
    if (!ParameterizedType.class.isAssignableFrom(genericType.getClass())) {
      if (genericType instanceof TypeVariable)
        genericType = getType(((TypeVariable<?>) genericType).getBounds(), pos);
      else if (genericType instanceof WildcardType) {
        final WildcardType wildcardType = (WildcardType) genericType;
        Type[] bounds = wildcardType.getLowerBounds();
        if (bounds.length == 0) bounds = wildcardType.getUpperBounds();
        genericType = getType(bounds, pos);
      }

      final Class<?> cls = (Class<?>) genericType;
      return cls.isArray() ? cls.getComponentType() : cls;
    }
    final ParameterizedType paramType = (ParameterizedType) genericType;
    final Type t = getType(paramType.getActualTypeArguments(), pos);
    return t instanceof Class ? (Class<?>) t : getActualType(t, pos);
  }
  protected void registerTypeVariablesOn(Type classType) {
    if (!(classType instanceof ParameterizedType)) {
      return;
    }
    ParameterizedType parameterizedType = (ParameterizedType) classType;
    TypeVariable[] typeParameters = ((Class<?>) parameterizedType.getRawType()).getTypeParameters();
    Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
    for (int i = 0; i < actualTypeArguments.length; i++) {
      TypeVariable typeParameter = typeParameters[i];
      Type actualTypeArgument = actualTypeArguments[i];

      if (actualTypeArgument instanceof WildcardType) {
        contextualActualTypeParameters.put(
            typeParameter, boundsOf((WildcardType) actualTypeArgument));
      } else {
        contextualActualTypeParameters.put(typeParameter, actualTypeArgument);
      }
      // logger.log("For '" + parameterizedType + "' found type variable : { '" + typeParameter +
      // "(" + System.identityHashCode(typeParameter) + ")" + "' : '" + actualTypeArgument + "(" +
      // System.identityHashCode(typeParameter) + ")" + "' }");
    }
  }
Пример #22
0
 // e.g. C[T1,T2]:Super[Int, T1] -> C[Int,Double]:Super[Int,Int]
 private final boolean instantiateCheck(
     Type<?>[] params, RuntimeType<?> rtt, Object o_or_any_or_subParams) {
   if (rtt.parents != null) {
     for (Type<?> t : rtt.parents) {
       if (javaClass.isAssignableFrom(t.getJavaClass())) {
         if (t instanceof ParameterizedType<?>) {
           ParameterizedType<?> pt = (ParameterizedType<?>) t;
           Type<?>[] origTypeArgumentsT = pt.getActualTypeArguments();
           Type<?>[] resolvedTypeArgumentsT = new Type<?>[origTypeArgumentsT.length];
           for (int i = 0; i < origTypeArgumentsT.length; i++) {
             resolvedTypeArgumentsT[i] =
                 resolveUnresolvedType(rtt, o_or_any_or_subParams, origTypeArgumentsT[i]);
           }
           if (isAssignableFrom(params, pt.getRawType(), resolvedTypeArgumentsT)) {
             return true;
           }
         }
       }
     }
   }
   return false;
 }
Пример #23
0
 private static Type<?> resolveUnresolvedType(
     RuntimeType<?> rtt, Object o_or_any_or_subParams, Type<?> origTypeArgument) {
   Type<?> t = origTypeArgument;
   while (t instanceof UnresolvedType) {
     int index = ((UnresolvedType) t).getIndex();
     if (o_or_any_or_subParams instanceof Any) {
       Any any = (Any) o_or_any_or_subParams;
       t = index == -1 ? rtt : any.$getParam(index);
     } else if (o_or_any_or_subParams instanceof Type<?>[]) {
       Type<?>[] paramsRTT = (Type<?>[]) o_or_any_or_subParams;
       t = index == -1 ? rtt : paramsRTT[index];
     } else {
       assert (index == -1);
       t = rtt;
     }
   }
   if (t instanceof ParameterizedType<?>) {
     ParameterizedType<?> pt = (ParameterizedType<?>) t;
     Type<?>[] origTypeArgumentsT = pt.getActualTypeArguments();
     Type<?>[] resolvedTypeArgumentsT = new Type<?>[origTypeArgumentsT.length];
     for (int i = 0; i < origTypeArgumentsT.length; i++) {
       resolvedTypeArgumentsT[i] =
           resolveUnresolvedType(rtt, o_or_any_or_subParams, origTypeArgumentsT[i]);
     }
     if (origTypeArgumentsT.length == 1) {
       t = ParameterizedType.make(pt.getRawType(), resolvedTypeArgumentsT[0]);
     } else if (origTypeArgumentsT.length == 2) {
       t =
           ParameterizedType.make(
               pt.getRawType(), resolvedTypeArgumentsT[0], resolvedTypeArgumentsT[1]);
     } else {
       t = ParameterizedType.make(pt.getRawType(), resolvedTypeArgumentsT);
     }
   }
   return t;
 }
Пример #24
0
  static <T> MvelExpression<T> createExpression(Method finderMethod) {
    Finder finder;
    checkArgument(null != (finder = finderMethod.getAnnotation(Finder.class)));
    checkArgument(finderMethod.getReturnType() == Iterator.class);

    // collect the return type, argument types and names from the method declaration
    ParameterizedType genericReturnType = (ParameterizedType) finderMethod.getGenericReturnType();
    @SuppressWarnings({"unchecked"})
    Class<T> resultType = (Class<T>) genericReturnType.getActualTypeArguments()[0];
    List<String> argumentNames = Lists.newArrayList();
    List<Class<?>> argumentTypes = Lists.newArrayList(finderMethod.getParameterTypes());
    Annotation[][] annotations = finderMethod.getParameterAnnotations();
    for (int i = 0; i < annotations.length; i++) {
      String name = ":" + (1 + i);
      for (int j = 0; j < annotations[i].length; j++) {
        if (annotations[i][j] instanceof Named) {
          Named named = (Named) annotations[i][j];
          name = named.value();
        }
      }
      argumentNames.add(name);
    }
    return createExpression(finder, resultType, argumentNames, argumentTypes);
  }
Пример #25
0
 public void appendToSignature(
     int iParam,
     ValueType type,
     Class<?> parameterType,
     Type genericParameterType,
     StringBuilder javaSig,
     StringBuilder dcSig,
     StringBuilder asmSig) {
   char dcChar;
   String javaChar, asmChar = null;
   switch (type) {
     case eVoidValue:
       dcChar = DC_SIGCHAR_VOID;
       javaChar = "V";
       break;
     case eIntValue:
       dcChar = DC_SIGCHAR_INT;
       javaChar = "I";
       break;
     case eLongValue:
       dcChar = DC_SIGCHAR_LONGLONG;
       javaChar = "J";
       break;
     case eSizeTValue:
       javaChar = "J";
       if (Platform.SIZE_T_SIZE == 8) {
         dcChar = DC_SIGCHAR_LONGLONG;
       } else {
         dcChar = DC_SIGCHAR_INT;
         direct = false;
       }
       break;
     case eShortValue:
       dcChar = DC_SIGCHAR_SHORT;
       javaChar = "S";
       break;
     case eDoubleValue:
       dcChar = DC_SIGCHAR_DOUBLE;
       javaChar = "D";
       break;
     case eFloatValue:
       dcChar = DC_SIGCHAR_FLOAT;
       javaChar = "F";
       break;
     case eByteValue:
       dcChar = DC_SIGCHAR_CHAR;
       javaChar = "B";
       break;
     case eBooleanValue:
       dcChar = DC_SIGCHAR_BOOL;
       javaChar = "Z";
       break;
     case eWCharValue:
       switch (Platform.WCHAR_T_SIZE) {
         case 1:
           dcChar = DC_SIGCHAR_CHAR;
           direct = false;
           break;
         case 2:
           dcChar = DC_SIGCHAR_SHORT;
           break;
         case 4:
           dcChar = DC_SIGCHAR_INT;
           direct = false;
           break;
         default:
           throw new RuntimeException(
               "Unhandled sizeof(wchar_t) in GetJavaTypeSignature: " + Platform.WCHAR_T_SIZE);
       }
       javaChar = "C";
       break;
     case eIntFlagSet:
       dcChar = DC_SIGCHAR_INT;
       javaChar =
           "L" + parameterType.getName().replace('.', '/') + ";"; // "Lorg/bridj/ValuedEnum;";
       direct = false;
       break;
     case eCLongObjectValue:
       dcChar = DC_SIGCHAR_POINTER;
       javaChar = "Lorg/bridj/CLong;";
       direct = false;
       break;
     case eSizeTObjectValue:
       dcChar = DC_SIGCHAR_POINTER;
       javaChar = "Lorg/bridj/SizeT;";
       direct = false;
       break;
     case eTimeTObjectValue:
       dcChar = DC_SIGCHAR_POINTER;
       javaChar = "Lorg/bridj/TimeT;";
       direct = false;
       break;
     case ePointerValue:
       dcChar = DC_SIGCHAR_POINTER;
       javaChar = "L" + parameterType.getName().replace('.', '/') + ";";
       //                javaChar = "Lorg/bridj/Pointer;";
       direct = false;
       break;
     case eNativeObjectValue:
       dcChar = DC_SIGCHAR_STRUCT; // TODO : unroll struct signature ?
       javaChar = "L" + parameterType.getName().replace('.', '/') + ";";
       direct = false;
       //              if (parameterType.equals(declaringClass)) {
       //                    // special case of self-returning pointers
       //                    dcChar = DC_SIGCHAR_POINTER;
       break;
     case eEllipsis:
       javaChar = "[Ljava/lang/Object;";
       dcChar = '?';
       break;
     default:
       direct = false;
       throw new RuntimeException("Unhandled " + ValueType.class.getSimpleName() + ": " + type);
   }
   if (genericParameterType instanceof ParameterizedType && iParam < 0) {
     ParameterizedType pt = (ParameterizedType) genericParameterType;
     // TODO handle all cases !!!
     Type[] ts = pt.getActualTypeArguments();
     if (ts != null && ts.length == 1) {
       Type t = ts[0];
       if (t instanceof ParameterizedType) t = ((ParameterizedType) t).getRawType();
       if (t instanceof Class) {
         Class c = (Class) t;
         if (javaChar.endsWith(";")) {
           asmChar =
               javaChar.substring(0, javaChar.length() - 1)
                   + "<*L"
                   + c.getName().replace('.', '/')
                   + ";>";
           // asmChar += ";";
         }
       }
     }
   }
   if (javaSig != null) javaSig.append(javaChar);
   if (asmChar == null) asmChar = javaChar;
   if (asmSig != null) asmSig.append(asmChar);
   if (dcSig != null) dcSig.append(dcChar);
 }
Пример #26
0
 static String toString(ParameterizedType pt) {
   String s = toString(pt.getActualTypeArguments());
   return String.format("%s<%s>", toString(pt.getRawType()), s);
 }
  /**
   * Parses object with follow rules:
   *
   * <p>1. All fields should had a public access. 2. The name of the filed should be fully equal to
   * name of JSONObject key. 3. Supports parse of all Java primitives, all {@link String}, arrays of
   * primitive types, {@link String}s and {@link com.vk.sdk.api.model.VKApiModel}s, list
   * implementation line {@link VKList}, {@link com.vk.sdk.api.model.VKAttachments.VKAttachment} or
   * {@link com.vk.sdk.api.model.VKPhotoSizes}, {@link com.vk.sdk.api.model.VKApiModel}s.
   *
   * <p>4. Boolean fields defines by vk_int == 1 expression.
   *
   * @param object object to initialize
   * @param source data to read values
   * @param <T> type of result
   * @return initialized according with given data object
   * @throws org.json.JSONException if source object structure is invalid
   */
  @SuppressWarnings({"rawtypes", "unchecked"})
  public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
      source = source.optJSONObject("response");
    }
    if (source == null) {
      return object;
    }
    for (Field field : object.getClass().getFields()) {
      field.setAccessible(true);
      String fieldName = field.getName();
      Class<?> fieldType = field.getType();

      Object value = source.opt(fieldName);
      if (value == null) {
        continue;
      }
      try {
        if (fieldType.isPrimitive() && value instanceof Number) {
          Number number = (Number) value;
          if (fieldType.equals(int.class)) {
            field.setInt(object, number.intValue());
          } else if (fieldType.equals(long.class)) {
            field.setLong(object, number.longValue());
          } else if (fieldType.equals(float.class)) {
            field.setFloat(object, number.floatValue());
          } else if (fieldType.equals(double.class)) {
            field.setDouble(object, number.doubleValue());
          } else if (fieldType.equals(boolean.class)) {
            field.setBoolean(object, number.intValue() == 1);
          } else if (fieldType.equals(short.class)) {
            field.setShort(object, number.shortValue());
          } else if (fieldType.equals(byte.class)) {
            field.setByte(object, number.byteValue());
          }
        } else {
          Object result = field.get(object);
          if (value.getClass().equals(fieldType)) {
            result = value;
          } else if (fieldType.isArray() && value instanceof JSONArray) {
            result = parseArrayViaReflection((JSONArray) value, fieldType);
          } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
            Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
            result = constructor.newInstance((JSONArray) value);
          } else if (VKAttachments.class.isAssignableFrom(fieldType)
              && value instanceof JSONArray) {
            Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
            result = constructor.newInstance((JSONArray) value);
          } else if (VKList.class.equals(fieldType)) {
            ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
            Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
            if (VKApiModel.class.isAssignableFrom(genericType)
                && Parcelable.class.isAssignableFrom(genericType)
                && Identifiable.class.isAssignableFrom(genericType)) {
              if (value instanceof JSONArray) {
                result = new VKList((JSONArray) value, genericType);
              } else if (value instanceof JSONObject) {
                result = new VKList((JSONObject) value, genericType);
              }
            }
          } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
            result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
          }
          field.set(object, result);
        }
      } catch (InstantiationException e) {
        throw new JSONException(e.getMessage());
      } catch (IllegalAccessException e) {
        throw new JSONException(e.getMessage());
      } catch (NoSuchMethodException e) {
        throw new JSONException(e.getMessage());
      } catch (InvocationTargetException e) {
        throw new JSONException(e.getMessage());
      } catch (NoSuchMethodError e) {
        // Примечание Виталия:
        // Вы не поверите, но у некоторых вендоров getFields() вызывает ВОТ ЭТО.
        // Иногда я всерьез задумываюсь, правильно ли я поступил, выбрав Android в качестве
        // платформы разработки.
        throw new JSONException(e.getMessage());
      }
    }
    return object;
  }
Пример #28
0
  protected void _resolveBindings(Type t) {
    if (t == null) return;

    Class<?> raw;
    if (t instanceof ParameterizedType) {
      ParameterizedType pt = (ParameterizedType) t;
      Type[] args = pt.getActualTypeArguments();
      if (args != null && args.length > 0) {
        Class<?> rawType = (Class<?>) pt.getRawType();
        TypeVariable<?>[] vars = rawType.getTypeParameters();
        if (vars.length != args.length) {
          throw new IllegalArgumentException(
              "Strange parametrized type (in class "
                  + rawType.getName()
                  + "): number of type arguments != number of type parameters ("
                  + args.length
                  + " vs "
                  + vars.length
                  + ")");
        }
        for (int i = 0, len = args.length; i < len; ++i) {
          TypeVariable<?> var = vars[i];
          String name = var.getName();
          if (_bindings == null) {
            _bindings = new LinkedHashMap<String, JavaType>();
          } else {
            /* 24-Mar-2010, tatu: Better ensure that we do not overwrite something
             *  collected earlier (since we descend towards super-classes):
             */
            if (_bindings.containsKey(name)) continue;
          }
          // first: add a placeholder to prevent infinite loops
          _addPlaceholder(name);
          // then resolve type
          _bindings.put(name, _typeFactory._constructType(args[i], this));
        }
      }
      raw = (Class<?>) pt.getRawType();
    } else if (t instanceof Class<?>) {
      raw = (Class<?>) t;
      /* [JACKSON-677]: If this is an inner class then the generics are defined on the
       * enclosing class so we have to check there as well.  We don't
       * need to call getEnclosingClass since anonymous classes declare
       * generics
       */
      _resolveBindings(raw.getDeclaringClass());
      /* 24-Mar-2010, tatu: Can not have true generics definitions, but can
       *   have lower bounds ("<T extends BeanBase>") in declaration itself
       */
      TypeVariable<?>[] vars = raw.getTypeParameters();
      if (vars != null && vars.length > 0) {
        JavaType[] typeParams = null;

        if (_contextType != null && raw.isAssignableFrom(_contextType.getRawClass())) {
          typeParams = _typeFactory.findTypeParameters(_contextType, raw);
        }

        for (int i = 0; i < vars.length; i++) {
          TypeVariable<?> var = vars[i];

          String name = var.getName();
          Type varType = var.getBounds()[0];
          if (varType != null) {
            if (_bindings == null) {
              _bindings = new LinkedHashMap<String, JavaType>();
            } else { // and no overwriting...
              if (_bindings.containsKey(name)) continue;
            }
            _addPlaceholder(name); // to prevent infinite loops

            if (typeParams != null) {
              _bindings.put(name, typeParams[i]);
            } else {
              _bindings.put(name, _typeFactory._constructType(varType, this));
            }
          }
        }
      }
    } else { // probably can't be any of these... so let's skip for now
      // if (type instanceof GenericArrayType) {
      // if (type instanceof TypeVariable<?>) {
      // if (type instanceof WildcardType) {
      return;
    }
    // but even if it's not a parameterized type, its super types may be:
    _resolveBindings(raw.getGenericSuperclass());
    for (Type intType : raw.getGenericInterfaces()) {
      _resolveBindings(intType);
    }
  }
Пример #29
0
 private ClassNode configureParameterizedType(ParameterizedType parameterizedType) {
   ClassNode base = configureType(parameterizedType.getRawType());
   GenericsType[] gts = configureTypeArguments(parameterizedType.getActualTypeArguments());
   base.setGenericsTypes(gts);
   return base;
 }
Пример #30
0
  /**
   * Gets the actual type arguments that are used in a given implementation of a given generic base
   * class or interface. (Based on code copyright 2007 by Ian Robertson).
   *
   * @param base the generic base class or interface
   * @param implementation the type (potentially) implementing the given base class or interface
   * @return a list of the raw classes for the actual type arguments.
   */
  @NotNull
  public static List<Class<?>> getTypeArguments(
      @NotNull Class<?> base, @NotNull Class<?> implementation) {
    Map<Type, Type> resolvedTypes = new HashMap<Type, Type>();

    // first we need to resolve all supertypes up to the required base class or interface
    // and find the right Type for it
    Type type;

    Queue<Type> toCheck = new LinkedList<Type>();
    toCheck.add(implementation);
    while (true) {
      // if we have checked everything and not found the base class we return an empty list
      if (toCheck.isEmpty()) return ImmutableList.of();

      type = toCheck.remove();
      Class<?> clazz;

      if (type instanceof Class) {
        // there is no useful information for us in raw types, so just keep going up the inheritance
        // chain
        clazz = (Class) type;
        if (base.isInterface()) {
          // if we are actually looking for the type parameters to an interface we also need to
          // look at all the ones implemented by the given current one
          toCheck.addAll(Arrays.asList(clazz.getGenericInterfaces()));
        }
      } else if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        clazz = (Class) parameterizedType.getRawType();

        // for instances of ParameterizedType we extract and remember all type arguments
        TypeVariable<?>[] typeParameters = clazz.getTypeParameters();
        Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
        for (int i = 0; i < actualTypeArguments.length; i++) {
          resolvedTypes.put(typeParameters[i], actualTypeArguments[i]);
        }
      } else {
        return ImmutableList.of();
      }

      // we can stop if we have reached the sought for base type
      if (base.equals(getClass(type))) break;

      toCheck.add(clazz.getGenericSuperclass());
    }

    // finally, for each actual type argument provided to baseClass,
    // determine (if possible) the raw class for that type argument.
    Type[] actualTypeArguments;
    if (type instanceof Class) {
      actualTypeArguments = ((Class) type).getTypeParameters();
    } else {
      actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
    }
    List<Class<?>> typeArgumentsAsClasses = new ArrayList<Class<?>>();
    // resolve types by chasing down type variables.
    for (Type baseType : actualTypeArguments) {
      while (resolvedTypes.containsKey(baseType)) {
        baseType = resolvedTypes.get(baseType);
      }
      typeArgumentsAsClasses.add(getClass(baseType));
    }
    return typeArgumentsAsClasses;
  }