Beispiel #1
0
 private static final TypeVariable<?> resolve(
     final TypeVariable<?> typeVar, final TypeVariable<?>[] declaredVars) {
   for (TypeVariable<?> declaredVar : declaredVars) {
     if (typeVar.getName().equals(declaredVar.getName())) {
       return declaredVar;
     }
   }
   return null;
 }
Beispiel #2
0
 private ClassNode configureTypeVariableReference(TypeVariable tv) {
   ClassNode cn = ClassHelper.makeWithoutCaching(tv.getName());
   cn.setGenericsPlaceHolder(true);
   ClassNode cn2 = ClassHelper.makeWithoutCaching(tv.getName());
   cn2.setGenericsPlaceHolder(true);
   GenericsType[] gts = new GenericsType[] {new GenericsType(cn2)};
   cn.setGenericsTypes(gts);
   cn.setRedirect(ClassHelper.OBJECT_TYPE);
   return cn;
 }
Beispiel #3
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;
    }
  }
  /** Private recursive helper function to actually do the type-safe checking of assignability. */
  private static boolean isAssignableFrom(
      Type from, ParameterizedType to, Map<String, Type> typeVarMap) {

    if (from == null) {
      return false;
    }

    if (to.equals(from)) {
      return true;
    }

    // First figure out the class and any type information.
    Class<?> clazz = getRawType(from);
    ParameterizedType ptype = null;
    if (from instanceof ParameterizedType) {
      ptype = (ParameterizedType) from;
    }

    // Load up parameterized variable info if it was parameterized.
    if (ptype != null) {
      Type[] tArgs = ptype.getActualTypeArguments();
      TypeVariable<?>[] tParams = clazz.getTypeParameters();
      for (int i = 0; i < tArgs.length; i++) {
        Type arg = tArgs[i];
        TypeVariable<?> var = tParams[i];
        while (arg instanceof TypeVariable) {
          TypeVariable<?> v = (TypeVariable<?>) arg;
          arg = typeVarMap.get(v.getName());
        }
        typeVarMap.put(var.getName(), arg);
      }

      // check if they are equivalent under our current mapping.
      if (typeEquals(ptype, to, typeVarMap)) {
        return true;
      }
    }

    for (Type itype : clazz.getGenericInterfaces()) {
      if (isAssignableFrom(itype, to, new HashMap<String, Type>(typeVarMap))) {
        return true;
      }
    }

    // Interfaces didn't work, try the superclass.
    Type sType = clazz.getGenericSuperclass();
    if (isAssignableFrom(sType, to, new HashMap<String, Type>(typeVarMap))) {
      return true;
    }

    return false;
  }
Beispiel #5
0
 @Override
 public boolean equals(Object obj) {
   if (NativeTypeVariableEquals.NATIVE_TYPE_VARIABLE_ONLY) {
     // equal only to our TypeVariable implementation with identical bounds
     if (obj != null
         && Proxy.isProxyClass(obj.getClass())
         && Proxy.getInvocationHandler(obj) instanceof TypeVariableInvocationHandler) {
       TypeVariableInvocationHandler typeVariableInvocationHandler =
           (TypeVariableInvocationHandler) Proxy.getInvocationHandler(obj);
       TypeVariableImpl<?> that = typeVariableInvocationHandler.typeVariableImpl;
       return name.equals(that.getName())
           && genericDeclaration.equals(that.getGenericDeclaration())
           && bounds.equals(that.bounds);
     }
     return false;
   } else {
     // equal to any TypeVariable implementation regardless of bounds
     if (obj instanceof TypeVariable) {
       TypeVariable<?> that = (TypeVariable<?>) obj;
       return name.equals(that.getName())
           && genericDeclaration.equals(that.getGenericDeclaration());
     }
     return false;
   }
 }
Beispiel #6
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 #7
0
 private Class<?> extractRawInjectionClass(
     Class<?> injectedClass, TypeVariable<?> injectionTypeVariable) {
   int index = 0;
   for (TypeVariable<?> typeVariable :
       injectionTypeVariable.getGenericDeclaration().getTypeParameters()) {
     if (injectionTypeVariable.getName().equals(typeVariable.getName())) {
       return (Class<?>) getActualType(injectedClass, index);
     }
     index++;
   }
   throw new IllegalArgumentException(
       "Could not extract the rawInjectionClass of "
           + injectedClass
           + " and "
           + injectionTypeVariable);
 }
 public boolean equals(Object o) {
   if (!(o instanceof TypeVariable)) return false;
   TypeVariable tv = (TypeVariable) o;
   return equal(name, tv.getName())
       && equal(gd, tv.getGenericDeclaration())
       && Arrays.equals(bounds, tv.getBounds());
 }
 /**
  * Lookup a type variable in the scope, using its name. Returns null if no type variable with this
  * name is declared in this scope or any of its surrounding scopes.
  *
  * @param name - the name of the type variable being looked up
  * @return the requested type variable, if found
  */
 public TypeVariable<?> lookup(String name) {
   TypeVariable<?>[] tas = getRecvr().getTypeParameters();
   for (TypeVariable<?> tv : tas) {
     if (tv.getName().equals(name)) {
       return tv;
     }
   }
   return getEnclosingScope().lookup(name);
 }
 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));
   }
 }
Beispiel #11
0
 /*     */ public JavaType getType(TypeBindings bindings) /*     */ {
   /*  66 */ TypeVariable[] localTypeParams = this._constructor.getTypeParameters();
   /*     */
   /*  68 */ if ((localTypeParams != null) && (localTypeParams.length > 0)) {
     /*  69 */ bindings = bindings.childInstance();
     /*  70 */ for (TypeVariable var : localTypeParams) {
       /*  71 */ String name = var.getName();
       /*     */
       /*  73 */ bindings._addPlaceholder(name);
       /*     */
       /*  75 */ Type lowerBound = var.getBounds()[0];
       /*  76 */ JavaType type =
           lowerBound == null
               ? TypeFactory.fastSimpleType(Object.class)
               : TypeFactory.type(lowerBound, bindings);
       /*     */
       /*  78 */ bindings.addBinding(var.getName(), type);
       /*     */ }
     /*     */ }
   /*  81 */ return TypeFactory.type(getGenericType(), bindings);
   /*     */ }
  public static void main(String... args) {
    try {
      Class<?> c = Class.forName(args[0]);
      out.format("Class:%n  %s%n%n", c.getCanonicalName());
      out.format("Modifiers:%n  %s%n%n", Modifier.toString(c.getModifiers()));

      out.format("Type Parameters:%n");
      TypeVariable<?>[] tv = c.getTypeParameters();
      if (tv.length != 0) {
        out.format("  ");
        for (TypeVariable<?> t : tv) out.format("%s ", t.getName());
        out.format("%n%n");
      } else {
        out.format("  -- No Type Parameters --%n%n");
      }

      out.format("Implemented Interfaces:%n");
      Type[] intfs = c.getGenericInterfaces();
      if (intfs.length != 0) {
        for (Type intf : intfs) out.format("  %s%n", intf.toString());
        out.format("%n");
      } else {
        out.format("  -- No Implemented Interfaces --%n%n");
      }

      out.format("Inheritance Path:%n");
      List<Class<?>> l = new ArrayList<Class<?>>();
      printAncestor(c, l);
      if (l.size() != 0) {
        for (Class<?> cl : l) out.format("  %s%n", cl.getCanonicalName());
        out.format("%n");
      } else {
        out.format("  -- No Super Classes --%n%n");
      }

      out.format("Annotations:%n");
      Annotation[] ann = c.getAnnotations();
      if (ann.length != 0) {
        for (Annotation a : ann) out.format("  %s%n", a.toString());
        out.format("%n");
      } else {
        out.format("  -- No Annotations --%n%n");
      }

      // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
      x.printStackTrace();
    }
  }
  /**
   * Returns the actual type for a given generic type.
   *
   * @param initialType The initial type, which may be generic.
   * @param genericType The generic type information if any.
   * @return The actual type.
   */
  private Class<?> getJavaActualType(Class<?> initialType, Type genericType) {
    Class<?> result = initialType;

    try {
      if (genericType instanceof TypeVariable<?>) {
        TypeVariable<?> genericTypeVariable = (TypeVariable<?>) genericType;
        String genericTypeName = genericTypeVariable.getName();
        result = getJavaActualType(getResourceClass(), genericTypeName);
      }
    } catch (Throwable t) {
      t.printStackTrace();
    }

    return result;
  }
Beispiel #14
0
 /**
  * Resolves {@code var} using the encapsulated type mapping. If it maps to yet another
  * non-reified type or has bounds, {@code forDependants} is used to do further resolution, which
  * doesn't try to resolve any type variable on generic declarations that are already being
  * resolved.
  *
  * <p>Should only be called and overridden by {@link #resolve(TypeVariable)}.
  */
 Type resolveInternal(TypeVariable<?> var, TypeTable forDependants) {
   Type type = map.get(var);
   if (type == null) {
     Type[] bounds = var.getBounds();
     if (bounds.length == 0) {
       return var;
     }
     return Types.newTypeVariable(
         var.getGenericDeclaration(),
         var.getName(),
         new TypeResolver(forDependants).resolveTypes(bounds));
   }
   // in case the type is yet another type variable.
   return new TypeResolver(forDependants).resolveType(type);
 }
  private void buildGenericTypeVariables(Class<?>[] genericTypes) {
    if (samType.getTypeParameters().length != genericTypes.length)
      throw new LambdaException(
          "SAM class [%s] requires [%d] generic type variables, but only [%d] where provided",
          samType.getName(), samType.getTypeParameters().length, genericTypes.length);

    for (int i = 0; i < samType.getTypeParameters().length; i++) {
      TypeVariable typeVariable = samType.getTypeParameters()[i];
      for (Type bound : typeVariable.getBounds())
        if (bound instanceof Class<?> && !((Class) bound).isAssignableFrom(genericTypes[i]))
          throw new LambdaException(
              "SAM class [%s] generic type variable [%d, %s] is not compatible with generic parameter [%s]",
              samType.getName(), i, samType.getTypeParameters()[i].toString(), genericTypes[i]);
      materializedTypeVariableses.add(
          new MaterializedTypeVariable(typeVariable.getName(), genericTypes[i]));
    }
  }
Beispiel #16
0
  /**
   * Find the index of the TypeVariable in the classes parameters. The offset can be used on a
   * subclass to find the actual type.
   *
   * @param typeVariable - the type variable in question.
   * @return the index of the type variable in its declaring class/method/constructor's type
   *     parameters.
   */
  private static int getTypeVariableIndex(final TypeVariable typeVariable) {
    // the label from the class (the T in List<T>, the K or V in Map<K,V>, etc)
    final String typeVarName = typeVariable.getName();
    final TypeVariable[] typeParameters = typeVariable.getGenericDeclaration().getTypeParameters();
    for (int typeArgumentIndex = 0;
        typeArgumentIndex < typeParameters.length;
        typeArgumentIndex++) {
      // The .equals for TypeVariable may not be compatible, a name check should be sufficient.
      if (typeParameters[typeArgumentIndex].getName().equals(typeVarName)) return typeArgumentIndex;
    }

    // The only way this could happen is if the TypeVariable is hand built incorrectly, or it's
    // corrupted.
    throw new RuntimeException(
        String.format(
            "%s does not have a TypeVariable matching %s",
            typeVariable.getGenericDeclaration(), typeVariable));
  }
 @TestTargetNew(
     level = TestLevel.SUFFICIENT,
     notes = "Missing tests for TypeNotPresentException, MalformedParameterizedTypeException",
     method = "getGenericComponentType",
     args = {})
 public void testGetGenericComponentType() throws Exception {
   @SuppressWarnings("unchecked")
   Class<? extends A> clazz = GenericArrayTypeTest.A.class;
   Field field = clazz.getDeclaredField("array");
   Type genericType = field.getGenericType();
   assertInstanceOf(GenericArrayType.class, genericType);
   Type componentType = ((GenericArrayType) genericType).getGenericComponentType();
   assertEquals(getTypeParameter(clazz), componentType);
   assertInstanceOf(TypeVariable.class, componentType);
   TypeVariable<?> componentTypeVariable = (TypeVariable<?>) componentType;
   assertEquals("T", componentTypeVariable.getName());
   assertEquals(clazz, componentTypeVariable.getGenericDeclaration());
 }
Beispiel #18
0
 public boolean equals(Object var1) {
   if (Types.NativeTypeVariableEquals.NATIVE_TYPE_VARIABLE_ONLY) {
     if (!(var1 instanceof Types.TypeVariableImpl)) {
       return false;
     } else {
       Types.TypeVariableImpl var3 = (Types.TypeVariableImpl) var1;
       return this.name.equals(var3.getName())
           && this.genericDeclaration.equals(var3.getGenericDeclaration())
           && this.bounds.equals(var3.bounds);
     }
   } else if (!(var1 instanceof TypeVariable)) {
     return false;
   } else {
     TypeVariable var2 = (TypeVariable) var1;
     return this.name.equals(var2.getName())
         && this.genericDeclaration.equals(var2.getGenericDeclaration());
   }
 }
 protected static JavaType _resolveVariableViaSubTypes(
     HierarchicType leafType, String variableName, TypeBindings bindings) {
   // can't resolve raw types; possible to have as-of-yet-unbound types too:
   if (leafType != null && leafType.isGeneric()) {
     TypeVariable<?>[] typeVariables = leafType.getRawClass().getTypeParameters();
     for (int i = 0, len = typeVariables.length; i < len; ++i) {
       TypeVariable<?> tv = typeVariables[i];
       if (variableName.equals(tv.getName())) {
         // further resolution needed?
         Type type = leafType.asGeneric().getActualTypeArguments()[i];
         if (type instanceof TypeVariable<?>) {
           return _resolveVariableViaSubTypes(
               leafType.getSubType(), ((TypeVariable<?>) type).getName(), bindings);
         }
         // no we're good for the variable (but it may have parameterization of its own)
         return instance._fromType(type, bindings);
       }
     }
   }
   return instance._unknownType();
 }
  protected JavaType _fromVariable(TypeVariable<?> type, TypeBindings context) {
    /* 26-Sep-2009, tatus: It should be possible to try "partial"
     *  resolution; meaning that it is ok not to find bindings.
     *  For now this is indicated by passing null context.
     */
    if (context == null) {
      return _unknownType();
    }

    // Ok: here's where context might come in handy!
    String name = type.getName();
    JavaType actualType = context.findType(name);
    if (actualType != null) {
      return actualType;
    }

    /* 29-Jan-2010, tatu: We used to throw exception here, if type was
     *   bound: but the problem is that this can occur for generic "base"
     *   method, overridden by sub-class. If so, we will want to ignore
     *   current type (for method) since it will be masked.
     */
    Type[] bounds = type.getBounds();

    // With type variables we must use bound information.
    // Theoretically this gets tricky, as there may be multiple
    // bounds ("... extends A & B"); and optimally we might
    // want to choose the best match. Also, bounds are optional;
    // but here we are lucky in that implicit "Object" is
    // added as bounds if so.
    // Either way let's just use the first bound, for now, and
    // worry about better match later on if there is need.

    /* 29-Jan-2010, tatu: One more problem are recursive types
     *   (T extends Comparable<T>). Need to add "placeholder"
     *   for resolution to catch those.
     */
    context._addPlaceholder(name);
    return _fromType(bounds[0], context);
  }
Beispiel #21
0
 private static boolean isAssignableFrom(Type object, ParameterizedType parameterizedType, Map<String, Type> map) {
     int n2;
     if (object == null) {
         return false;
     }
     if (parameterizedType.equals(object)) {
         return true;
     }
     Class class_ = $Gson$Types.getRawType((Type)object);
     ParameterizedType parameterizedType2 = null;
     if (object instanceof ParameterizedType) {
         parameterizedType2 = (ParameterizedType)object;
     }
     if (parameterizedType2 != null) {
         Type[] arrtype = parameterizedType2.getActualTypeArguments();
         TypeVariable<Class<?>>[] arrtypeVariable = class_.getTypeParameters();
         for (n2 = 0; n2 < arrtype.length; ++n2) {
             object = arrtype[n2];
             TypeVariable typeVariable = arrtypeVariable[n2];
             while (object instanceof TypeVariable) {
                 object = map.get(((TypeVariable)object).getName());
             }
             map.put(typeVariable.getName(), (Type)object);
         }
         if (TypeToken.typeEquals(parameterizedType2, parameterizedType, map)) {
             return true;
         }
     }
     object = class_.getGenericInterfaces();
     int n3 = object.length;
     for (n2 = 0; n2 < n3; ++n2) {
         if (!TypeToken.isAssignableFrom(object[n2], parameterizedType, new HashMap<String, Type>(map))) continue;
         return true;
     }
     return TypeToken.isAssignableFrom(class_.getGenericSuperclass(), parameterizedType, new HashMap<String, Type>(map));
 }
 /** Generates the signature for the given constructor */
 private String signature(Constructor<?> constructor) {
   StringBuilder builder = new StringBuilder();
   if (constructor.getTypeParameters().length > 0) {
     builder.append('<');
     for (TypeVariable<?> typeVariable : constructor.getTypeParameters()) {
       builder.append(typeVariable.getName());
       for (java.lang.reflect.Type bound : typeVariable.getBounds()) {
         builder.append(':');
         visitType(bound, builder);
       }
     }
     builder.append('>');
   }
   builder.append('(');
   for (java.lang.reflect.Type paramType : constructor.getGenericParameterTypes()) {
     visitType(paramType, builder);
   }
   builder.append(")V");
   for (java.lang.reflect.Type exceptionType : constructor.getGenericExceptionTypes()) {
     builder.append('^');
     visitType(exceptionType, builder);
   }
   return builder.toString();
 }
  @SuppressWarnings({"unchecked", "rawtypes"})
  public final void parseArray(PBDeserializer parser, Type objectType, Collection array) {
    Type itemType = this.itemType;
    ;

    if (itemType instanceof TypeVariable && objectType instanceof ParameterizedType) {
      TypeVariable typeVar = (TypeVariable) itemType;
      ParameterizedType paramType = (ParameterizedType) objectType;

      Class<?> objectClass = null;
      if (paramType.getRawType() instanceof Class) {
        objectClass = (Class<?>) paramType.getRawType();
      }

      int paramIndex = -1;
      if (objectClass != null) {
        for (int i = 0, size = objectClass.getTypeParameters().length; i < size; ++i) {
          TypeVariable item = objectClass.getTypeParameters()[i];
          if (item.getName().equals(typeVar.getName())) {
            paramIndex = i;
            break;
          }
        }
      }

      if (paramIndex != -1) {
        itemType = paramType.getActualTypeArguments()[paramIndex];
      }
    }

    if (deserializer == null) {
      deserializer = parser.getDeserializer(itemType);
    }

    try {
      // int tmpTag = parser.getTheCodedInputStream().readTag();
      int tmpListItemCnt = parser.getTheCodedInputStream().readInt32();

      for (int i = 0; i < tmpListItemCnt; i++) {
        byte tmpIsNull = parser.getTheCodedInputStream().readRawByte();
        if (tmpIsNull == 0) {
          if (deserializer instanceof JavaObjectDeserializer) {
          } else {
            byte tmpType = parser.getTheCodedInputStream().readRawByte();
            if (com.jd.glowworm.asm.Type.OBJECT == tmpType) {
              if (deserializer
                  .getClass()
                  .getName()
                  .startsWith(ASMDeserializerFactory.DeserializerClassName_prefix)) {
                parser.getTheCodedInputStream().readString();
              }
            }
          }
          Object val = deserializer.deserialze(parser, itemType, null);
          array.add(val);
        } else {
          array.add(null);
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Beispiel #24
0
  private static void typeToString(StringBuilder sb, Type type, Set<Type> visited) {
    if (type instanceof ParameterizedType) {
      ParameterizedType parameterizedType = (ParameterizedType) type;
      final Class<?> rawType = (Class<?>) parameterizedType.getRawType();
      sb.append(rawType.getName());
      boolean first = true;
      for (Type typeArg : parameterizedType.getActualTypeArguments()) {
        if (first) {
          first = false;
        } else {
          sb.append(", ");
        }
        sb.append('<');
        typeToString(sb, typeArg, visited);
        sb.append('>');
      }
    } else if (type instanceof WildcardType) {
      WildcardType wildcardType = (WildcardType) type;
      sb.append('?');

      // According to
      // JLS(http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.5.1):
      // - Lower and upper can't coexist: (for instance, this is not allowed: <? extends
      // List<String> & super MyInterface>)
      // - Multiple bounds are not supported (for instance, this is not allowed: <? extends
      // List<String> & MyInterface>)

      final Type bound;
      if (wildcardType.getLowerBounds().length != 0) {
        sb.append(" super ");
        bound = wildcardType.getLowerBounds()[0];
      } else {
        sb.append(" extends ");
        bound = wildcardType.getUpperBounds()[0];
      }
      typeToString(sb, bound, visited);
    } else if (type instanceof TypeVariable<?>) {
      TypeVariable<?> typeVariable = (TypeVariable<?>) type;
      sb.append(typeVariable.getName());

      // prevent cycles in case: <T extends List<T>>

      if (!visited.contains(type)) {
        visited.add(type);
        sb.append(" extends ");
        boolean first = true;
        for (Type bound : typeVariable.getBounds()) {
          if (first) {
            first = false;
          } else {
            sb.append(" & ");
          }
          typeToString(sb, bound, visited);
        }
        visited.remove(type);
      }
    } else if (type instanceof GenericArrayType) {
      GenericArrayType genericArrayType = (GenericArrayType) type;
      typeToString(genericArrayType.getGenericComponentType());
      sb.append(genericArrayType.getGenericComponentType());
      sb.append("[]");
    } else if (type instanceof Class) {
      Class<?> typeClass = (Class<?>) type;
      sb.append(typeClass.getName());
    } else {
      throw new IllegalArgumentException("Unsupported type: " + type);
    }
  }
 private String nameFor(TypeVariable<?> variable) {
   return StringUtils.lowercaseFirst(variable.getName());
 }
Beispiel #26
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);
    }
  }
 XTypeVariable(XTypeFactory typeFactory, TypeVariable typeVariable) {
   _typeFactory = typeFactory;
   _typeVariable = typeVariable;
   _name = typeVariable.getName();
 }
Beispiel #28
0
 private GenericsType configureTypeVariableDefinition(TypeVariable tv) {
   return configureTypeVariableDefinition(
       configureTypeVariableReference(tv.getName()), configureTypes(tv.getBounds()));
 }