Exemple #1
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;
   }
 }
Exemple #2
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());
   }
 }
Exemple #3
0
 /** Returns the most elemental class associated with {@link genericType} May return null */
 public static Class<?> classFromType(Type genericType) {
   Class<?> defKlass;
   if (genericType == null) {
     return null;
   }
   if (genericType instanceof Class<?>) {
     defKlass = (Class<?>) genericType;
   } else if (genericType instanceof ParameterizedType) {
     ParameterizedType pt = (ParameterizedType) genericType;
     Type typeArgs[] = pt.getActualTypeArguments();
     if (typeArgs.length != 1) {
       // Odd - better to ignore this
       return null;
     }
     return classFromType(typeArgs[0]);
   } else if (genericType instanceof GenericArrayType) {
     GenericArrayType gat = (GenericArrayType) genericType;
     defKlass = gat.getGenericComponentType().getClass();
   } else if (genericType instanceof TypeVariable<?>) {
     TypeVariable<?> tv = (TypeVariable<?>) genericType;
     defKlass = tv.getClass();
   } else {
     LOG.debug("classFromType unknown instance type [" + genericType.toString() + "] - ignoring");
     defKlass = null;
   }
   return defKlass;
 }
 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());
 }
Exemple #5
0
 /** Returns the most elemental class associated with {@link genericType} May return null */
 public static boolean representsMultipleElements(Type genericType) {
   Class<?> defKlass = null;
   if (genericType == null) {
     return false;
   }
   if (genericType instanceof Class<?>) {
     defKlass = (Class<?>) genericType;
     return Collection.class.isAssignableFrom(defKlass);
   } else if (genericType instanceof ParameterizedType) {
     // e.g. java.util.List<com.zimbra.soap.type.AttributeName>
     ParameterizedType pt = (ParameterizedType) genericType;
     Type rawType = pt.getRawType();
     if (rawType instanceof Class<?>) {
       return Collection.class.isAssignableFrom((Class<?>) rawType);
     }
     return false;
   } else if (genericType instanceof GenericArrayType) {
     return true;
   } else if (genericType instanceof TypeVariable<?>) {
     TypeVariable<?> tv = (TypeVariable<?>) genericType;
     return Collection.class.isAssignableFrom(tv.getClass());
   } else {
     return false;
   }
 }
 public static Class<?> getActualClass(final Type type, final Map<TypeVariable<?>, Type> map) {
   if (Class.class.isInstance(type)) {
     return Class.class.cast(type);
   }
   if (ParameterizedType.class.isInstance(type)) {
     return getActualClass(ParameterizedType.class.cast(type).getRawType(), map);
   }
   if (WildcardType.class.isInstance(type)) {
     return getActualClass(WildcardType.class.cast(type).getUpperBounds()[0], map);
   }
   if (TypeVariable.class.isInstance(type)) {
     final TypeVariable<?> typeVariable = TypeVariable.class.cast(type);
     if (map.containsKey(typeVariable)) {
       return getActualClass(map.get(typeVariable), map);
     }
     return getActualClass(typeVariable.getBounds()[0], map);
   }
   if (GenericArrayType.class.isInstance(type)) {
     final GenericArrayType genericArrayType = GenericArrayType.class.cast(type);
     final Class<?> componentClass =
         getActualClass(genericArrayType.getGenericComponentType(), map);
     return Array.newInstance(componentClass, 0).getClass();
   }
   return null;
 }
Exemple #7
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;
 }
Exemple #8
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;
 }
 private static void assertThatTypeVariableDoesParameterizeAClass(TypeVariable<?> var) {
   if (!(var.getGenericDeclaration() instanceof Class<?>)) {
     throw new IllegalArgumentException(
         String.format(
             "Type parameters are supported only for classes, but %s is a declared for %s",
             var, var.getGenericDeclaration()));
   }
 }
Exemple #10
0
 /** getDefaultType的统一入口 */
 private static Type getDefaultType(Type type, Map<TypeVariable<?>, Type> handledArguments) {
   if (type instanceof TypeVariable<?>) {
     TypeVariable<?> tv = (TypeVariable<?>) type;
     return getDefaultType(tv.getBounds(), handledArguments, tv);
   } else {
     return getDefaultType(type, handledArguments, null);
   }
 }
 /**
  * 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);
 }
Exemple #12
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;
 }
 public void testWithMutualRecursiveBoundInTypeVariable() throws Exception {
   ParameterizedType paramType =
       (ParameterizedType)
           new WithGenericBound<String>() {}.getTargetType("withMutualRecursiveBound");
   TypeVariable<?> k = (TypeVariable<?>) paramType.getActualTypeArguments()[0];
   TypeVariable<?> v = (TypeVariable<?>) paramType.getActualTypeArguments()[1];
   assertEquals(Types.newParameterizedType(List.class, v), k.getBounds()[0]);
   assertEquals(Types.newParameterizedType(List.class, k), v.getBounds()[0]);
 }
 public void testTypeAnno() throws Exception {
   CtClass cc = sloader.get("test5.TypeAnno");
   cc.getClassFile().compact();
   cc.writeFile();
   Object obj = make(cc.getName());
   TypeVariable<?> t = obj.getClass().getTypeParameters()[0];
   Annotation[] annos = t.getAnnotations();
   assertEquals("@test5.TypeAnnoA()", annos[0].toString());
 }
Exemple #15
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;
 }
Exemple #16
0
  public HelloRowMapper() {

    TypeVariable<? extends Class<? extends HelloRowMapper>>[] sd =
        this.getClass().getTypeParameters();

    TypeVariable<?> pp = sd[0];
    Class pps = (Class) pp.getGenericDeclaration();

    System.out.println(sd);
  }
  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);
      }
    }
  }
Exemple #18
0
 /** Returns a new {@code TypeResolver} with {@code variable} mapping to {@code type}. */
 final TypeTable where(Map<? extends TypeVariable<?>, ? extends Type> mappings) {
   ImmutableMap.Builder<TypeVariable<?>, Type> builder = ImmutableMap.builder();
   builder.putAll(map);
   for (Map.Entry<? extends TypeVariable<?>, ? extends Type> mapping : mappings.entrySet()) {
     TypeVariable<?> variable = mapping.getKey();
     Type type = mapping.getValue();
     checkArgument(!variable.equals(type), "Type variable %s bound to itself", variable);
     builder.put(variable, type);
   }
   return new TypeTable(builder.build());
 }
 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));
   }
 }
  /**
   * Method to resolve a TypeVariable to its most <a
   * href="http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#112582">reifiable</a>
   * form.
   *
   * <p>How to resolve a TypeVariable:<br>
   * All of the TypeVariables defined by a generic class will be given a Type by any class that
   * extends it. The Type given may or may not be reifiable; it may be another TypeVariable for
   * instance.
   *
   * <p>Consider <br>
   * <i>class Pair&gt;A,B> { A getA(){...}; ...}</i><br>
   * <i>class StringLongPair extends Pair&gt;String, Long> { }</i><br>
   * To resolve the actual return type of Pair.getA() you must first resolve the TypeVariable "A".
   * We can do that by first finding the index of "A" in the Pair.class.getTypeParameters() array of
   * TypeVariables.
   *
   * <p>To get to the Type provided by StringLongPair you access the generics information by calling
   * StringLongPair.class.getGenericSuperclass; this will be a ParameterizedType. ParameterizedType
   * gives you access to the actual type arguments provided to Pair by StringLongPair. The array is
   * in the same order as the array in Pair.class.getTypeParameters so you can use the index we
   * discovered earlier to extract the Type; String.class.
   *
   * <p>When extracting Types we only have to consider the superclass hierarchy and not the
   * interfaces implemented by the class. When a class implements a generic interface it must
   * provide types for the interface and any generic methods implemented from the interface will be
   * re-defined by the class with its generic type variables.
   *
   * @param typeVariable - the type variable to resolve.
   * @param containingType - the shallowest class in the class hierarchy (furthest from Object)
   *     where typeVariable is defined.
   * @return a Type that has had all possible TypeVariables resolved that have been defined between
   *     the type variable declaration and the containingType.
   */
  private static Type resolve(TypeVariable typeVariable, Type containingType) {
    // The generic declaration is either a Class, Method or Constructor
    final GenericDeclaration genericDeclaration = typeVariable.getGenericDeclaration();

    if (!(genericDeclaration instanceof Class)) {
      // It's a method or constructor. The best we can do here is try to resolve the bounds
      // e.g. <T extends E> T getT(T param){} where E is defined by the class.
      final Type bounds0 = typeVariable.getBounds()[0];
      return resolve(bounds0, containingType);
    }

    final Class typeVariableOwner = (Class) genericDeclaration;

    // find the typeOwner in the containingType's hierarchy
    final LinkedList<Type> stack = new LinkedList<Type>();

    // If you pass a List<Long> as the containingType then the TypeVariable is going to be resolved
    // by the
    // containingType and not the super class.
    if (containingType instanceof ParameterizedType) {
      stack.add(containingType);
    }

    Class theClass = asClass(containingType);
    Type genericSuperclass = theClass.getGenericSuperclass();
    while (genericSuperclass != null
        && // true for interfaces with no superclass
        !theClass.equals(Object.class)
        && !theClass.equals(typeVariableOwner)) {
      stack.addFirst(genericSuperclass);
      theClass = asClass(genericSuperclass);
      genericSuperclass = theClass.getGenericSuperclass();
    }

    int i = getTypeVariableIndex(typeVariable);
    Type resolved = typeVariable;
    for (Type t : stack) {
      if (t instanceof ParameterizedType) {
        resolved = ((ParameterizedType) t).getActualTypeArguments()[i];
        if (resolved instanceof Class) return resolved;
        if (resolved instanceof TypeVariable) {
          // Need to look at the next class in the hierarchy
          i = getTypeVariableIndex((TypeVariable) resolved);
          continue;
        }
        return resolve(resolved, containingType);
      }
    }

    // the only way we get here is if resolved is still a TypeVariable, otherwise an
    // exception is thrown or a value is returned.
    return ((TypeVariable) resolved).getBounds()[0];
  }
  @Nullable
  public static Type resolveVariable(
      TypeVariable variable, final Class classType, boolean resolveInInterfacesOnly) {
    final Class aClass = getRawType(classType);
    int index = ArrayUtilRt.find(ReflectionCache.getTypeParameters(aClass), variable);
    if (index >= 0) {
      return variable;
    }

    final Class[] classes = ReflectionCache.getInterfaces(aClass);
    final Type[] genericInterfaces = ReflectionCache.getGenericInterfaces(aClass);
    for (int i = 0; i <= classes.length; i++) {
      Class anInterface;
      if (i < classes.length) {
        anInterface = classes[i];
      } else {
        anInterface = ReflectionCache.getSuperClass(aClass);
        if (resolveInInterfacesOnly || anInterface == null) {
          continue;
        }
      }
      final Type resolved = resolveVariable(variable, anInterface);
      if (resolved instanceof Class || resolved instanceof ParameterizedType) {
        return resolved;
      }
      if (resolved instanceof TypeVariable) {
        final TypeVariable typeVariable = (TypeVariable) resolved;
        index = ArrayUtilRt.find(ReflectionCache.getTypeParameters(anInterface), typeVariable);
        if (index < 0) {
          LOG.error(
              "Cannot resolve type variable:\n"
                  + "typeVariable = "
                  + typeVariable
                  + "\n"
                  + "genericDeclaration = "
                  + declarationToString(typeVariable.getGenericDeclaration())
                  + "\n"
                  + "searching in "
                  + declarationToString(anInterface));
        }
        final Type type =
            i < genericInterfaces.length ? genericInterfaces[i] : aClass.getGenericSuperclass();
        if (type instanceof Class) {
          return Object.class;
        }
        if (type instanceof ParameterizedType) {
          return getActualTypeArguments((ParameterizedType) type)[index];
        }
        throw new AssertionError("Invalid type: " + type);
      }
    }
    return null;
  }
  /** 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;
  }
 private boolean shouldTypeBeAdded(final Type t2, final ParameterizedType parameterizedType) {
   if (!(t2 instanceof TypeVariable)) {
     return true;
   }
   TypeVariable<?> typeVariable = (TypeVariable<?>) t2;
   final Type[] bounds = typeVariable.getBounds();
   for (Type bound : bounds) {
     if (bound instanceof ParameterizedType && bound.equals(parameterizedType)) {
       return false;
     }
   }
   return true;
 }
Exemple #24
0
 public static Class resolveToClass(Type type) {
   if (type == null) {
     throw new NullPointerException("No null type accepted");
   }
   if (type instanceof Class<?>) {
     return (Class<?>) type;
   } else if (type instanceof TypeVariable) {
     TypeVariable resolvedTypeVariable = (TypeVariable) type;
     return resolveToClass(resolvedTypeVariable.getBounds()[0]);
   } else {
     throw new UnsupportedOperationException(
         "Type resolution of " + type + " not yet implemented");
   }
 }
  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();
    }
  }
Exemple #26
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);
 }
  /**
   * 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;
  }
Exemple #28
0
 public Class<T> getGenericClass(int i) {
   System.out.println(this.getClass());
   System.out.println(this.getClass().getSuperclass());
   Type genType = this.getClass().getGenericSuperclass();
   Type[] args = ((ParameterizedType) genType).getActualTypeArguments();
   if (i > -1 && i < args.length) {
     if (args[i] instanceof TypeVariable) {
       TypeVariable t = (TypeVariable) args[i];
       return (Class) t.getGenericDeclaration();
     } else {
       return (Class) args[i];
     }
   } else {
     return null;
   }
 }
Exemple #29
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);
 }
 /**
  * True if this type variable is one of the java.* special cases
  *
  * @return
  */
 private boolean isSpecialCase(TypeVariable<?> typeVariable) {
   for (Type bound : typeVariable.getBounds()) {
     Class<?> clazz = GenericTypeReflector.erase(bound);
     if (specialCases.contains(clazz)) return true;
   }
   return false;
 }