/**
   * Determines the key type for a Map.
   *
   * @param type The parametrized type.
   * @param path The path to the type, used in exception message.
   * @return The key type.
   */
  public static Type[] mapTypes(Type type, String path) {
    if (type instanceof Class) {
      Class c = (Class) type;
      type = c.getGenericSuperclass();
      if (!(isGenericMap(type))) {
        Type[] types = c.getGenericInterfaces();
        if (types != null && types.length > 0) {
          for (Type t : types) {
            if (isGenericMap(t)) {
              type = t;
              break;
            }
          }
        }
      }
    }

    if (type instanceof ParameterizedType) {
      ParameterizedType parameterizedType = (ParameterizedType) type;
      Class<?> rawType = (Class<?>) parameterizedType.getRawType();
      if (Map.class.isAssignableFrom(rawType)) {
        return parameterizedType.getActualTypeArguments();
      }
    }

    throw new CollectionExpressionException(
        "The method or member ["
            + path
            + "] returns a simple Map. Unable to determine the "
            + "types of the Map. Please make this method or member generic so that the correct type can be determined.");
  }
 @Override
 public <T> void extract(ModelSchemaExtractionContext<T> extractionContext) {
   Type type = extractionContext.getType().getType();
   if (!(type instanceof Class)) {
     return;
   }
   Class<?> contractType = (Class<?>) type;
   if (!contractType.isInterface()) {
     return;
   }
   if (contractType.getGenericInterfaces().length != 1) {
     return;
   }
   Type superType = contractType.getGenericInterfaces()[0];
   if (!(superType instanceof ParameterizedType)) {
     return;
   }
   ParameterizedType parameterizedSuperType = (ParameterizedType) superType;
   if (!parameterizedSuperType.getRawType().equals(ModelMap.class)) {
     return;
   }
   ModelType<?> elementType = ModelType.of(parameterizedSuperType.getActualTypeArguments()[0]);
   Class<?> proxyImpl = generator.generate(ModelMapGroovyDecorator.Managed.class, contractType);
   extractionContext.found(
       new SpecializedMapSchema<T>(extractionContext.getType(), elementType, proxyImpl));
 }
Beispiel #3
0
 public static boolean isAssignableFrom(
     Class<?> rawType1, Type[] actualTypeArguments1, Type type2) {
   if (type2 instanceof ParameterizedType) {
     ParameterizedType parameterizedType = (ParameterizedType) type2;
     if (parameterizedType.getRawType() instanceof Class<?>) {
       if (isAssignableFrom(
           rawType1,
           actualTypeArguments1,
           (Class<?>) parameterizedType.getRawType(),
           parameterizedType.getActualTypeArguments())) {
         return true;
       }
     }
   } else if (type2 instanceof Class<?>) {
     Class<?> clazz = (Class<?>) type2;
     if (isAssignableFrom(rawType1, actualTypeArguments1, clazz, EMPTY_TYPES)) {
       return true;
     }
   } else if (type2 instanceof TypeVariable<?>) {
     TypeVariable<?> typeVariable = (TypeVariable<?>) type2;
     if (isTypeBounded(rawType1, actualTypeArguments1, typeVariable.getBounds())) {
       return true;
     }
   }
   return false;
 }
 private Object convert(
     Type targetType, Object sourceObject, Action<? super SourceObjectMapping> mapping) {
   if (targetType instanceof ParameterizedType) {
     ParameterizedType parameterizedTargetType = (ParameterizedType) targetType;
     if (parameterizedTargetType.getRawType() instanceof Class) {
       Class<?> rawClass = (Class<?>) parameterizedTargetType.getRawType();
       if (Iterable.class.isAssignableFrom(rawClass)) {
         Type targetElementType = getElementType(parameterizedTargetType, 0);
         return convertCollectionInternal(
             rawClass, targetElementType, (Iterable<?>) sourceObject, mapping);
       }
       if (Map.class.isAssignableFrom(rawClass)) {
         Type targetKeyType = getElementType(parameterizedTargetType, 0);
         Type targetValueType = getElementType(parameterizedTargetType, 1);
         return convertMap(
             rawClass, targetKeyType, targetValueType, (Map<?, ?>) sourceObject, mapping);
       }
     }
   }
   if (targetType instanceof Class) {
     if (((Class) targetType).isPrimitive()) {
       return sourceObject;
     }
     return adapt((Class) targetType, sourceObject, mapping);
   }
   throw new UnsupportedOperationException(
       String.format("Cannot convert object of %s to %s.", sourceObject.getClass(), targetType));
 }
Beispiel #5
0
 private static boolean isCollection(Type type) {
   if (type instanceof ParameterizedType) {
     ParameterizedType ptype = (ParameterizedType) type;
     return Collection.class.isAssignableFrom((Class<?>) ptype.getRawType())
         || Map.class.isAssignableFrom((Class<?>) ptype.getRawType());
   }
   return Collection.class.isAssignableFrom((Class<?>) type);
 }
  private static ClassTypePair resolveTypeVariable(
      ParameterizedType pt, Class c, Class dc, TypeVariable tv, Map<TypeVariable, Type> map) {
    Type[] typeArguments = pt.getActualTypeArguments();

    TypeVariable[] typeParameters = c.getTypeParameters();

    Map<TypeVariable, Type> submap = new HashMap<TypeVariable, Type>();
    for (int i = 0; i < typeArguments.length; i++) {
      // Substitute a type variable with the Java class
      if (typeArguments[i] instanceof TypeVariable) {
        Type t = map.get(typeArguments[i]);
        submap.put(typeParameters[i], t);
      } else {
        submap.put(typeParameters[i], typeArguments[i]);
      }
    }

    if (c == dc) {
      Type t = submap.get(tv);
      if (t instanceof Class) {
        return new ClassTypePair((Class) t);
      } else if (t instanceof GenericArrayType) {
        t = ((GenericArrayType) t).getGenericComponentType();
        if (t instanceof Class) {
          c = (Class) t;
          try {
            return new ClassTypePair(getArrayClass(c));
          } catch (Exception e) {
          }
          return null;
        } else if (t instanceof ParameterizedType) {
          Type rt = ((ParameterizedType) t).getRawType();
          if (rt instanceof Class) {
            c = (Class) rt;
          } else {
            return null;
          }
          try {
            return new ClassTypePair(getArrayClass(c), t);
          } catch (Exception e) {
            return null;
          }
        } else {
          return null;
        }
      } else if (t instanceof ParameterizedType) {
        pt = (ParameterizedType) t;
        if (pt.getRawType() instanceof Class) {
          return new ClassTypePair((Class) pt.getRawType(), pt);
        } else return null;
      } else {
        return null;
      }
    } else {
      return resolveTypeVariable(c, dc, tv, submap);
    }
  }
  private void addType(Type cls, boolean allowArray) {
    if (cls instanceof Class) {
      if (globalAdapters.contains(cls)) {
        return;
      }
      if (((Class<?>) cls).isArray() && !allowArray) {
        addClass(((Class<?>) cls).getComponentType());
      } else {
        addClass((Class<?>) cls);
      }
    } else if (cls instanceof ParameterizedType) {
      final ParameterizedType parameterizedType = (ParameterizedType) cls;
      addType(parameterizedType.getRawType());
      if (!parameterizedType.getRawType().equals(Enum.class)) {
        for (Type t2 : parameterizedType.getActualTypeArguments()) {
          if (shouldTypeBeAdded(t2, parameterizedType)) {
            addType(t2);
          }
        }
      }
    } else if (cls instanceof GenericArrayType) {
      Class<?> ct;
      GenericArrayType gt = (GenericArrayType) cls;
      Type componentType = gt.getGenericComponentType();
      if (componentType instanceof Class) {
        ct = (Class<?>) componentType;
      } else {
        TypeVariable<?> tv = (TypeVariable<?>) componentType;
        Type[] bounds = tv.getBounds();
        if (bounds != null && bounds.length == 1) {
          if (bounds[0] instanceof Class) {
            ct = (Class<?>) bounds[0];
          } else {
            throw new IllegalArgumentException("Unable to determine type for: " + tv);
          }
        } else {
          throw new IllegalArgumentException("Unable to determine type for: " + tv);
        }
      }
      ct = Array.newInstance(ct, 0).getClass();

      addClass(ct);
    } else if (cls instanceof WildcardType) {
      for (Type t : ((WildcardType) cls).getUpperBounds()) {
        addType(t);
      }
      for (Type t : ((WildcardType) cls).getLowerBounds()) {
        addType(t);
      }
    } else if (cls instanceof TypeVariable) {
      for (Type t : ((TypeVariable<?>) cls).getBounds()) {
        addType(t);
      }
    }
  }
Beispiel #8
0
  /** Returns true if {@code a} and {@code b} are equal. */
  public static boolean equals(Type a, Type b) {
    if (a == b) {
      // also handles (a == null && b == null)
      return true;

    } else if (a instanceof Class) {
      // Class already specifies equals().
      return a.equals(b);

    } else if (a instanceof ParameterizedType) {
      if (!(b instanceof ParameterizedType)) {
        return false;
      }

      // TODO: save a .clone() call
      ParameterizedType pa = (ParameterizedType) a;
      ParameterizedType pb = (ParameterizedType) b;
      return equal(pa.getOwnerType(), pb.getOwnerType())
          && pa.getRawType().equals(pb.getRawType())
          && Arrays.equals(pa.getActualTypeArguments(), pb.getActualTypeArguments());

    } else if (a instanceof GenericArrayType) {
      if (!(b instanceof GenericArrayType)) {
        return false;
      }

      GenericArrayType ga = (GenericArrayType) a;
      GenericArrayType gb = (GenericArrayType) b;
      return equals(ga.getGenericComponentType(), gb.getGenericComponentType());

    } else if (a instanceof WildcardType) {
      if (!(b instanceof WildcardType)) {
        return false;
      }

      WildcardType wa = (WildcardType) a;
      WildcardType wb = (WildcardType) b;
      return Arrays.equals(wa.getUpperBounds(), wb.getUpperBounds())
          && Arrays.equals(wa.getLowerBounds(), wb.getLowerBounds());

    } else if (a instanceof TypeVariable) {
      if (!(b instanceof TypeVariable)) {
        return false;
      }
      TypeVariable<?> va = (TypeVariable<?>) a;
      TypeVariable<?> vb = (TypeVariable<?>) b;
      return va.getGenericDeclaration() == vb.getGenericDeclaration()
          && va.getName().equals(vb.getName());

    } else {
      // This isn't a type we support. Could be a generic array type,
      // wildcard type, etc.
      return false;
    }
  }
Beispiel #9
0
 private static Type getDefaultType(
     Type type, Map<TypeVariable<?>, Type> handledArguments, TypeVariable<?> currentArgument) {
   if (type instanceof Class) {
     return type;
   } else if (type instanceof TypeVariable<?>) {
     Type handledArgument = handledArguments.get(type);
     if (handledArgument != null) {
       return handledArgument;
     }
     if (type == currentArgument) {
       // class Enum<E extends Enum<? extends E>> and class Enum<E extends Enum<E>>
       return currentArgument;
     }
     return null;
   } else if (type instanceof GenericArrayType) {
     Type componentType = ((GenericArrayType) type).getGenericComponentType();
     Type defaultComponentType = getDefaultType(componentType, handledArguments, currentArgument);
     if (defaultComponentType != null) {
       return new GenericArrayTypeImpl(defaultComponentType);
     }
     return null;
   } else if (type instanceof WildcardType) {
     Type[] varBounds = ((WildcardType) type).getUpperBounds();
     Type varType = getDefaultType(varBounds, handledArguments, currentArgument);
     if (varType != null) {
       return varType;
     }
     return null;
   } else {
     ParameterizedType parameterizedType = (ParameterizedType) type;
     Type[] vars =
         parameterizedType
             .getActualTypeArguments(); // F<T extends Serializable & List<? extends X>, X, Y
     // extends T>  -->>  ? extends X
     Type[] tranedArguments = new Type[vars.length];
     for (int i = 0; i < vars.length; i++) {
       Type var = vars[i];
       Type defaultVar = getDefaultType(var, handledArguments, currentArgument);
       if (defaultVar == null) {
         return null;
       } else if (defaultVar == currentArgument) {
         // class Enum<E extends Enum<? extends E>> vs class Enum<E extends Enum<E>>
         // 出现递归,则忽略所有参数? N extends Map<N, Object> ==>> Map
         // TODO N extends Map<N, Object> ==>> Map<Map<Map<...>>, Object>
         return parameterizedType.getRawType();
       } else {
         tranedArguments[i] = defaultVar;
       }
     }
     return new ParameterizedTypeImpl(parameterizedType.getRawType(), tranedArguments);
   }
 }
Beispiel #10
0
 /*
  * Enabled force condition propagation
  * Lifted jumps to return sites
  */
 private static boolean typeEquals(ParameterizedType arrtype, ParameterizedType arrtype2, Map<String, Type> map) {
     if (!arrtype.getRawType().equals(arrtype2.getRawType())) return false;
     arrtype = arrtype.getActualTypeArguments();
     arrtype2 = arrtype2.getActualTypeArguments();
     int n2 = 0;
     while (n2 < arrtype.length) {
         if (!TypeToken.matches(arrtype[n2], arrtype2[n2], map)) {
             return false;
         }
         ++n2;
     }
     return true;
 }
 /**
  * Checks if two parameterized types are exactly equal, under the variable replacement described
  * in the typeVarMap.
  */
 private static boolean typeEquals(
     ParameterizedType from, ParameterizedType to, Map<String, Type> typeVarMap) {
   if (from.getRawType().equals(to.getRawType())) {
     Type[] fromArgs = from.getActualTypeArguments();
     Type[] toArgs = to.getActualTypeArguments();
     for (int i = 0; i < fromArgs.length; i++) {
       if (!matches(fromArgs[i], toArgs[i], typeVarMap)) {
         return false;
       }
     }
     return true;
   }
   return false;
 }
Beispiel #12
0
 private static Class getClass(Type type) {
   if (type instanceof Class) {
     return (Class) type;
   } else if (type instanceof ParameterizedType) {
     ParameterizedType parameterizedType = (ParameterizedType) type;
     if (parameterizedType.getRawType() instanceof Class) {
       return (Class) parameterizedType.getRawType();
     }
   }
   throw new IllegalArgumentException(
       "Type parameter ["
           + type.toString()
           + "] not a class or "
           + "parameterized type whose raw type is a class");
 }
 public void testResolveToGenericArrayType() {
   GenericArrayType arrayType =
       (GenericArrayType) new Holder<List<int[][]>[]>() {}.getContentType();
   ParameterizedType listType = (ParameterizedType) arrayType.getGenericComponentType();
   assertEquals(List.class, listType.getRawType());
   assertEquals(Types.newArrayType(int[].class), listType.getActualTypeArguments()[0]);
 }
Beispiel #14
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());
   }
 }
Beispiel #15
0
  public static Class<?> getRawType(Type type) {
    if (type instanceof Class<?>) {
      // type is a normal class.
      return (Class<?>) type;

    } else if (type instanceof ParameterizedType) {
      ParameterizedType parameterizedType = (ParameterizedType) type;

      // I'm not exactly sure why getRawType() returns Type instead of Class.
      // Neal isn't either but suspects some pathological case related
      // to nested classes exists.
      Type rawType = parameterizedType.getRawType();
      // checkArgument(rawType instanceof Class,
      // "Expected a Class, but <%s> is of type %s", type, type.getClass().getName());
      return (Class<?>) rawType;

    } else if (type instanceof GenericArrayType) {
      // TODO: Is this sufficient?
      return Object[].class;

    } else if (type instanceof TypeVariable) {
      // we could use the variable's bounds, but that'll won't work if there are multiple.
      // having a raw type that's more general than necessary is okay
      return Object.class;

    } else {
      throw new IllegalArgumentException(
          "Expected a Class, ParameterizedType, or "
              + "GenericArrayType, but <"
              + type
              + "> is of type "
              + type.getClass().getName());
    }
  }
Beispiel #16
0
  private static GenericType getFieldType(
      VariableMapping currentMapping, Class<?> startClass, String fieldname) {
    Type type = null;
    Field field = null; // e.g. BClass<String, Integer> bObject;
    {
      Class<?> ownerClass = startClass;
      findfield:
      while (true) {
        Field[] fields = ownerClass.getDeclaredFields();
        for (Field f : fields) {
          if (f.getName().equals(fieldname)) {
            field = f;
            break findfield;
          }
        }
        // field not found so far
        // -> search superclass
        Type superType = ownerClass.getGenericSuperclass();
        if (superType instanceof ParameterizedType) {
          ParameterizedType parameterizedSuperType = (ParameterizedType) superType;
          currentMapping = new VariableMapping(currentMapping, parameterizedSuperType);
          ownerClass = (Class<?>) parameterizedSuperType.getRawType();
        } else if (superType instanceof Class<?>) {
          ownerClass = (Class<?>) superType;
        } else {
          throw new IllegalStateException();
        }
      }
    }

    type = field.getGenericType(); // e.g. BClass<String, Integer>

    return getGenericType(currentMapping, type);
  }
Beispiel #17
0
 private static VariableMapping resolveTypeVariableInParameterizedType(
     TypeVariable<?> var, ParameterizedType inParameterizedType, VariableMapping currentMapping) {
   assertThatTypeVariableDoesParameterizeAClass(var);
   currentMapping = new VariableMapping(currentMapping, inParameterizedType);
   Class<?> inClass = (Class<?>) inParameterizedType.getRawType();
   return resolveTypeVariableInClass(var, inClass, currentMapping);
 }
Beispiel #18
0
 /**
  * Returns the value of the given {@link TypeVariable} as a {@link GenericType}.
  *
  * @param variable must parameterize this type or one of it's super types
  * @return the actual value of the given {@link TypeVariable} as a {@link GenericType}
  * @throws IllegalArgumentException if the variable does not parameterize this type
  * @throws UnsupportedOperationException if the type parameter resolution is not supported for
  *     this type
  */
 public GenericType getTypeParameter(TypeVariable<? extends Class<?>> variable)
     throws IllegalArgumentException, IllegalStateException {
   assertThatTypeVariableDoesParameterizeAClass(variable);
   GenericType result = null;
   if (type instanceof Class<?>) {
     Class<?> cls = (Class<?>) type;
     // Class<?> parameterizedClass = (Class<?>)
     // variable.getGenericDeclaration();
     // // Break-Condition
     // if (parameterizedClass.equals(cls)) {
     // GenericType result = new GenericType(mapping, variable);
     // return result;
     // }
     VariableMapping aMapping = resolveTypeVariableInClass(variable, cls, mapping);
     if (aMapping != null) {
       result = getGenericType(aMapping, variable);
     }
   } else if (type instanceof ParameterizedType) {
     ParameterizedType pType = (ParameterizedType) type;
     Class<?> rawType = (Class<?>) pType.getRawType();
     VariableMapping aMapping = resolveTypeVariableInClass(variable, rawType, mapping);
     if (aMapping != null) {
       result = getGenericType(aMapping, variable);
     }
   } else {
     throw new UnsupportedOperationException(
         String.format("Type parameter resolution not supported for %s", type));
   }
   if (result == null) {
     throw new IllegalArgumentException(
         String.format("%s does not parameterize this type %s!", variable, type));
   } else {
     return result;
   }
 }
  public static Set<Class<?>> getReferencedClasses(
      Set<Type> referencedTypes, TypescriptServiceGeneratorConfiguration settings) {
    Set<Class<?>> ret = Sets.newHashSet();
    for (Type t : referencedTypes) {
      if (settings.ignoredClasses().contains(t)) {
        continue;
      }

      if (t instanceof Class && ((Class<?>) t).isEnum()) {
        ret.add((Class<?>) t);
        continue;
      }

      // dummy context used for below check
      Context nullContext =
          new Context(new SymbolTable(settings.getSettings()), settings.customTypeProcessor());
      // Don't add any classes that the user has made an exception for
      if (settings.customTypeProcessor().processType(t, nullContext) == null) {
        if (t instanceof Class) {
          ret.add((Class<?>) t);
        } else if (t instanceof ParameterizedType) {
          ParameterizedType parameterized = (ParameterizedType) t;
          ret.addAll(getReferencedClasses(Sets.newHashSet(parameterized.getRawType()), settings));
          ret.addAll(
              getReferencedClasses(
                  Sets.newHashSet(Arrays.asList(parameterized.getActualTypeArguments()).iterator()),
                  settings));
        }
      }
    }
    return ret;
  }
Beispiel #20
0
 /** 获取一个Type类型实际对应的Class */
 @SuppressWarnings("rawtypes")
 public static Class<?> getTypeClass(Type type) {
   Class<?> clazz = null;
   if (type instanceof Class<?>) {
     clazz = (Class<?>) type;
   } else if (type instanceof ParameterizedType) {
     ParameterizedType pt = (ParameterizedType) type;
     clazz = (Class<?>) pt.getRawType();
   } else if (type instanceof GenericArrayType) {
     GenericArrayType gat = (GenericArrayType) type;
     Class<?> typeClass = getTypeClass(gat.getGenericComponentType());
     return Array.newInstance(typeClass, 0).getClass();
   } else if (type instanceof TypeVariable) {
     TypeVariable tv = (TypeVariable) type;
     Type[] ts = tv.getBounds();
     if (ts != null && ts.length > 0) return getTypeClass(ts[0]);
   } else if (type instanceof WildcardType) {
     WildcardType wt = (WildcardType) type;
     Type[] t_low = wt.getLowerBounds(); // 取其下界
     if (t_low.length > 0) return getTypeClass(t_low[0]);
     Type[] t_up = wt.getUpperBounds(); // 没有下界?取其上界
     return getTypeClass(t_up[0]); // 最起码有Object作为上界
   }
   return clazz;
 }
  /**
   * Determines the component type. Lists is the first type, Map is the second type, etc.
   *
   * @param type The parametrized type.
   * @param path The path to the type, used in exception message.
   * @return The component type.
   */
  public static Type componentType(Type type, String path) {
    if (type instanceof ParameterizedType) {
      ParameterizedType parameterizedType = (ParameterizedType) type;
      Class<?> rawType = (Class<?>) parameterizedType.getRawType();
      if (Map.class.isAssignableFrom(rawType)) {
        return parameterizedType.getActualTypeArguments()[1];
      } else if (Collection.class.isAssignableFrom(rawType)) {
        return parameterizedType.getActualTypeArguments()[0];
      } else {
        throw new CollectionExpressionException("Unknown collection type [" + type + "]");
      }
    } else if (type instanceof GenericArrayType) {
      return ((GenericArrayType) type).getGenericComponentType();
    }

    Class<?> rawType = (Class<?>) type;
    if (Map.class == type || Collection.class == type) {
      throw new CollectionExpressionException(
          "The method or member ["
              + path
              + "] returns a simple "
              + "Map or Collection. Unable to determine the type of the Map or Collection. "
              + "Please make this method generic so that the correct type can be determined.");
    } else if (rawType.isArray()) {
      return rawType.getComponentType();
    }

    return rawType;
  }
Beispiel #22
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());
  }
 private void writeObject(
     ContentValues values, Object object, String columnName, ParameterizedType fieldType)
     throws IOException {
   if (object == null) return;
   final Type rawType = fieldType.getRawType();
   if (!(rawType instanceof Class)) throw new UnsupportedOperationException();
   final Class rawCls = (Class) rawType;
   if (List.class.isAssignableFrom(rawCls)) {
     values.put(
         columnName,
         LoganSquare.serialize((List) object, (Class) fieldType.getActualTypeArguments()[0]));
   } else if (Map.class.isAssignableFrom(rawCls)) {
     //noinspection unchecked
     values.put(
         columnName,
         LoganSquare.serialize((Map) object, (Class) fieldType.getActualTypeArguments()[1]));
   } else if (rawCls.isArray()) {
     final Class componentType = rawCls.getComponentType();
     values.put(
         columnName,
         LoganSquare.serialize((List) Arrays.asList((Object[]) object), componentType));
   } else {
     values.put(columnName, LoganSquare.serialize(object));
   }
 }
  @SuppressWarnings("unchecked")
  static Class<? extends Event<?>> getEventClass(Class<?> handlerClass) {

    for (Class<?> i : handlerClass.getInterfaces()) {
      if (EventHandler.class.equals(i)) {
        for (Type t : handlerClass.getGenericInterfaces()) {
          if (t instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) t;
            if (EventHandler.class.equals(pt.getRawType())) {

              return (Class<? extends Event<?>>) pt.getActualTypeArguments()[0];
            }
          }
        }
      } else if (EventHandler.class.isAssignableFrom(i)) {
        return getEventClass((Class<? extends EventHandler<?>>) i);
      }
    }

    if (EventHandler.class.isAssignableFrom(handlerClass.getSuperclass())) {
      return getEventClass((Class<?>) handlerClass.getSuperclass());
    }

    return null;
  }
 /**
  * Infer value type in one collection type
  *
  * @param genericType
  * @return
  */
 public static Type inferElementTypeIn(Type collectionType) {
   if (collectionType instanceof Class) {
     return Object.class;
   } else if (collectionType instanceof ParameterizedType) {
     ParameterizedType parameterizedCollectionType = (ParameterizedType) collectionType;
     Type collectionValueType = parameterizedCollectionType.getActualTypeArguments()[0];
     if (collectionValueType instanceof Class) {
       return (Class) collectionValueType;
     } else if (collectionValueType instanceof ParameterizedType) {
       ParameterizedType type = (ParameterizedType) collectionValueType;
       return type.getRawType();
     } else if (collectionValueType instanceof WildcardType) {
       throw new UnusableTypeException(
           "we can't infer element type in widlcard type " + collectionType.toString());
     } else if (collectionValueType instanceof TypeVariable) {
       throw new UnusableTypeException(
           "we can't infer element type in type variable " + collectionType.toString());
     }
   } else if (collectionType instanceof WildcardType) {
     throw new UnusableTypeException(
         "we can't infer element type in widlcard type " + collectionType.toString());
   } else if (collectionType instanceof TypeVariable) {
     throw new UnusableTypeException(
         "we can't infer element type in type variable " + collectionType.toString());
   }
   throw new UnusableTypeException("we can't infer element type in " + collectionType.toString());
 }
 private String nameFor(ParameterizedType type) {
   Class<?> raw = (Class<?>) type.getRawType();
   if (Collection.class.isAssignableFrom(raw)) {
     return nameFor(type.getActualTypeArguments()[0]) + "List";
   }
   return nameFor(raw);
 }
Beispiel #27
0
  /**
   * Creates the type, it's private so you must use fromType.
   *
   * @param type
   */
  private JavaType(Type type) {

    // the type
    this.type = type;

    // parameterized?
    parameterizedType =
        ParameterizedType.class.isInstance(type) ? ParameterizedType.class.cast(type) : null;

    // generic info
    genericInfo = parameterizedType != null;

    // get class
    if (Class.class.isInstance(type)) {
      clazz = Class.class.cast(type);
    } else if (parameterizedType != null) {
      clazz = Class.class.cast(parameterizedType.getRawType());
    } else {
      clazz = null;
    }

    // component type
    if (clazz != null && clazz.getComponentType() != null) {
      componentType = clazz.getComponentType();
    }

    // instantiable
    instantiable = clazz != null;

    // typeParameters
    typeParameters = parameterizedType != null ? parameterizedType.getActualTypeArguments() : null;

    // genericInfo
    genericInfo = typeParameters != null;
  }
Beispiel #28
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);
   }
 }
  @SuppressWarnings("unchecked")
  private static Class<?> getRawType(Type type) {
    if (type instanceof Class<?>) {
      // type is a normal class.
      return (Class<?>) type;
    } else if (type instanceof ParameterizedType) {
      ParameterizedType parameterizedType = (ParameterizedType) type;

      // I'm not exactly sure why getRawType() returns Type instead of Class.
      // Neal isn't either but suspects some pathological case related
      // to nested classes exists.
      Type rawType = parameterizedType.getRawType();
      if (rawType instanceof Class<?>) {
        return (Class<?>) rawType;
      }
      throw buildUnexpectedTypeError(rawType, Class.class);
    } else if (type instanceof GenericArrayType) {
      GenericArrayType genericArrayType = (GenericArrayType) type;

      // TODO(jleitch): This is not the most efficient way to handle generic
      // arrays, but is there another way to extract the array class in a
      // non-hacky way (i.e. using String value class names- "[L...")?
      Object rawArrayType =
          Array.newInstance(getRawType(genericArrayType.getGenericComponentType()), 0);
      return rawArrayType.getClass();
    } else {
      throw buildUnexpectedTypeError(type, ParameterizedType.class, GenericArrayType.class);
    }
  }
  /**
   * Get the parameterized class arguments for a declaring class that declares a generic interface
   * type.
   *
   * @param p the declaring class
   * @return the parameterized class arguments, or null if the generic interface type is not a
   *     parameterized type.
   */
  public static Class[] getParameterizedClassArguments(DeclaringClassInterfacePair p) {
    if (p.genericInterface instanceof ParameterizedType) {
      ParameterizedType pt = (ParameterizedType) p.genericInterface;
      Type[] as = pt.getActualTypeArguments();
      Class[] cas = new Class[as.length];

      for (int i = 0; i < as.length; i++) {
        Type a = as[i];
        if (a instanceof Class) {
          cas[i] = (Class) a;
        } else if (a instanceof ParameterizedType) {
          pt = (ParameterizedType) a;
          cas[i] = (Class) pt.getRawType();
        } else if (a instanceof TypeVariable) {
          ClassTypePair ctp =
              resolveTypeVariable(p.concreteClass, p.declaringClass, (TypeVariable) a);
          cas[i] = (ctp != null) ? ctp.c : Object.class;
        } else if (a instanceof GenericArrayType) {
          cas[i] = getClassOfType(a);
        }
      }
      return cas;
    } else {
      return null;
    }
  }