Ejemplo n.º 1
0
  public <T> Class<T> inferValueClassForListOrSet(Type genericType, Class<?> entityClass) {
    log.debug(
        "Infer parameterized value class for collection type {} of entity class {} ",
        genericType.toString(),
        entityClass.getCanonicalName());

    Class<T> valueClass;
    if (genericType instanceof ParameterizedType) {
      ParameterizedType pt = (ParameterizedType) genericType;
      Type[] actualTypeArguments = pt.getActualTypeArguments();
      if (actualTypeArguments.length > 0) {
        Type type = actualTypeArguments[actualTypeArguments.length - 1];
        valueClass = getClassFromType(type);
      } else {
        throw new AchillesBeanMappingException(
            "The type '"
                + genericType.getClass().getCanonicalName()
                + "' of the entity '"
                + entityClass.getCanonicalName()
                + "' should be parameterized");
      }
    } else {
      throw new AchillesBeanMappingException(
          "The type '"
              + genericType.getClass().getCanonicalName()
              + "' of the entity '"
              + entityClass.getCanonicalName()
              + "' should be parameterized");
    }

    log.trace("Inferred value class : {}", valueClass.getCanonicalName());

    return valueClass;
  }
Ejemplo n.º 2
0
  /**
   * 通过反射, 获得Class定义中声明的父类的泛型参数的类型. 如无法找到, 返回Object.class.
   *
   * <p>如public UserDao extends HibernateDao<User,Long>
   *
   * @param clazz clazz The class to introspect
   * @param index the Index of the generic ddeclaration,start from 0.
   * @return the index generic declaration, or Object.class if cannot be determined
   */
  @SuppressWarnings("rawtypes")
  public static Class getSuperClassGenricType(final Class clazz, final int index) {

    Type genType = clazz.getGenericSuperclass();

    if (!(genType.getClass().isAssignableFrom(ParameterizedType.class))) {
      log.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
      return Object.class;
    }

    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

    if (index >= params.length || index < 0) {
      log.warn(
          "Index: "
              + index
              + ", Size of "
              + clazz.getSimpleName()
              + "'s Parameterized Type: "
              + params.length);
      return Object.class;
    }
    if (!(params[index].getClass().isAssignableFrom(Class.class))) {
      log.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
      return Object.class;
    }

    return (Class) params[index];
  }
  protected Class<T> getTClass() {
    ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
    Type resultType = type.getActualTypeArguments()[0];
    // ImplForType, ParameterizedTypeImpl
    //        if ("ParameterizedTypeImpl".equals(resultType.getClass().getSimpleName()) ||
    // "ImplForType".equals(resultType.getClass().getSimpleName())) {
    //            try {
    //                Field field = resultType.getClass().getDeclaredField("rawTypeName");
    //                field.setAccessible(true);
    //                String rawTypeName = (String) field.get(resultType);
    //                return (Class<T>) Class.forName(rawTypeName);
    //            } catch (Exception e) {
    //                return (Class<T>) Collection.class;
    //            }
    //        } else {
    //            return (Class<T>) resultType;
    //        }

    if (resultType instanceof Class) {
      return (Class<T>) resultType;
    } else {
      // 处理集合
      try {
        Field field = resultType.getClass().getDeclaredField("rawTypeName");
        field.setAccessible(true);
        String rawTypeName = (String) field.get(resultType);
        return (Class<T>) Class.forName(rawTypeName);
      } catch (Exception e) {
        return (Class<T>) Collection.class;
      }
    }
  }
Ejemplo n.º 4
0
  @Test
  public void testgeneric4() throws SecurityException, NoSuchMethodException {
    System.out.println("====  testgeneric4 ====");

    Type type = GenericUtils.newArrayType(String.class);
    System.out.println(type.getClass().getName());
    System.out.println("isRawArray:" + GenericUtils.isRawArray(type));
    System.out.println("rawType:" + GenericUtils.getRawClass(type));

    Class<?> c = new String[0].getClass();
    System.out.println(c.getClass().getName());
    System.out.println(c.getName());
    System.out.println(c);

    System.out.println(type.equals(c));
    System.out.println("====  testgeneric4b ====");
    FieldEx field = BeanUtils.getField(GenericTypeTemplateTest.class, "field1");
    System.out.println(field.getType().equals(c));
    System.out.println(field.getGenericType().equals(c)); // 当不是泛型时,返回的是class对象
    System.out.println(field.getType());
    System.out.println(field.getGenericType());
    System.out.println(type);
    System.out.println(field.getGenericType().equals(type));

    System.out.println("====  testgeneric4c ====");
    field = BeanUtils.getField(GenericTypeTemplateTest.class, "field2");
    System.out.println(field.getType());
    System.out.println(field.getGenericType());
    type = field.getGenericType();
    System.out.println("isRawArray:" + GenericUtils.isRawArray(type));
    System.out.println("rawType:" + GenericUtils.getRawClass(type));
    System.out.println(GenericUtils.getRawClass(type).equals(field.getType()));
  }
Ejemplo n.º 5
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());
    }
  }
Ejemplo n.º 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());
   }
 }
  /**
   * Resolve current method generic return type to a {@link GenericMetadataSupport}.
   *
   * @param method Method to resolve the return type.
   * @return {@link GenericMetadataSupport} representing this generic return type.
   */
  public GenericMetadataSupport resolveGenericReturnType(Method method) {
    Type genericReturnType = method.getGenericReturnType();
    // logger.log("Method '" + method.toGenericString() + "' has return type : " +
    // genericReturnType.getClass().getInterfaces()[0].getSimpleName() + " : " + genericReturnType);

    if (genericReturnType instanceof Class) {
      return new NotGenericReturnTypeSupport(genericReturnType);
    }
    if (genericReturnType instanceof ParameterizedType) {
      return new ParameterizedReturnType(
          this, method.getTypeParameters(), (ParameterizedType) method.getGenericReturnType());
    }
    if (genericReturnType instanceof TypeVariable) {
      return new TypeVariableReturnType(
          this, method.getTypeParameters(), (TypeVariable) genericReturnType);
    }

    throw new MockitoException(
        "Ouch, it shouldn't happen, type '"
            + genericReturnType.getClass().getCanonicalName()
            + "' on method : '"
            + method.toGenericString()
            + "' is not supported : "
            + genericReturnType);
  }
 protected static <T> T parseJson(Gson gson, InputStream stream, Type type) throws IOException {
   BufferedReader reader =
       new BufferedReader(new InputStreamReader(stream, HttpConnector.UTF_8), 2048);
   StringBuilder bld = new StringBuilder();
   String line;
   while ((line = reader.readLine()) != null) {
     bld.append(line);
     bld.append('\n');
   }
   try {
     return gson.fromJson(bld.toString(), type);
   } catch (JsonSyntaxException jpe) {
     if (type.getClass().getName().equals("com.puppetlabs.puppetdb.javaclient.model.Event")) {
       return (T) new Event();
     } else {
       throw new APIException("Parse exception converting JSON to object", jpe); // $NON-NLS-1$
     }
   } finally {
     try {
       reader.close();
     } catch (IOException ignored) {
       // Ignored
     }
   }
 }
Ejemplo n.º 9
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 TypeUsage toTypeUsage(Type parameterType) {
   if (parameterType instanceof Class) {
     TypeDefinition typeDefinition = new ReflectionBasedTypeDefinition(clazz);
     ReferenceTypeUsage referenceTypeUsage = new ReferenceTypeUsage(typeDefinition);
     return referenceTypeUsage;
   } else {
     throw new UnsupportedOperationException(parameterType.getClass().getCanonicalName());
   }
 }
Ejemplo n.º 11
0
 private static /* varargs */ AssertionError buildUnexpectedTypeError(Type type, Class<?> ... arrclass) {
     StringBuilder stringBuilder = new StringBuilder("Unexpected type. Expected one of: ");
     int n2 = arrclass.length;
     for (int i2 = 0; i2 < n2; ++i2) {
         stringBuilder.append(arrclass[i2].getName()).append(", ");
     }
     stringBuilder.append("but got: ").append(type.getClass().getName()).append(", for type token: ").append(type.toString()).append('.');
     return new AssertionError((Object)stringBuilder.toString());
 }
Ejemplo n.º 12
0
 public static Class<?> determineGenericsType(Type type) {
   Class<?> result = null;
   if (type != null && ParameterizedType.class.isAssignableFrom(type.getClass())) {
     Type genericType = ((ParameterizedType) type).getActualTypeArguments()[0];
     if (genericType != null) {
       result = (Class<?>) genericType;
     }
   }
   return result;
 }
Ejemplo n.º 13
0
 public static Class<?> getRawType(Type type) {
   if (type instanceof Class) {
     return (Class) type;
   }
   if (type instanceof ParameterizedType) {
     return getRawType(((ParameterizedType) type).getRawType());
   }
   throw new IllegalStateException(
       "unsupported type: " + type.getClass().getName() + " for " + type);
 }
Ejemplo n.º 14
0
  /**
   * A simplistic implementation, it may not handle all cases but it should handle enough.
   *
   * @param implementation the type for which the parameter requires a resolution
   * @param type the type that owns the parameter
   * @param parameterIndex the parameter index
   * @return the resolved type
   */
  public static Type resolve(Type implementation, Class<?> type, int parameterIndex) {
    if (implementation == null) {
      throw new NullPointerException();
    }

    //
    if (implementation == type) {
      TypeVariable<? extends Class<?>>[] tp = type.getTypeParameters();
      if (parameterIndex < tp.length) {
        return tp[parameterIndex];
      } else {
        throw new IllegalArgumentException();
      }
    } else if (implementation instanceof Class<?>) {
      Class<?> c = (Class<?>) implementation;
      Type gsc = c.getGenericSuperclass();
      Type resolved = null;
      if (gsc != null) {
        resolved = resolve(gsc, type, parameterIndex);
        if (resolved == null) {
          // Try with interface
        }
      }
      return resolved;
    } else if (implementation instanceof ParameterizedType) {
      ParameterizedType pt = (ParameterizedType) implementation;
      Type[] typeArgs = pt.getActualTypeArguments();
      Type rawType = pt.getRawType();
      if (rawType == type) {
        return typeArgs[parameterIndex];
      } else if (rawType instanceof Class<?>) {
        Class<?> classRawType = (Class<?>) rawType;
        Type resolved = resolve(classRawType, type, parameterIndex);
        if (resolved == null) {
          return null;
        } else if (resolved instanceof TypeVariable) {
          TypeVariable resolvedTV = (TypeVariable) resolved;
          TypeVariable[] a = classRawType.getTypeParameters();
          for (int i = 0; i < a.length; i++) {
            if (a[i].equals(resolvedTV)) {
              return resolve(implementation, classRawType, i);
            }
          }
          throw new AssertionError();
        } else {
          throw new UnsupportedOperationException("Cannot support resolution of " + resolved);
        }
      } else {
        throw new UnsupportedOperationException();
      }
    } else {
      throw new UnsupportedOperationException(
          "todo " + implementation + " " + implementation.getClass());
    }
  }
Ejemplo n.º 15
0
 @Override
 public boolean isWriteable(
     Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
   boolean result = false;
   if (Iterable.class.isAssignableFrom(type)
       && genericType.getClass().isAssignableFrom(ArtifactReadable.class)
       && MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) {
     result = true;
   }
   return result;
 }
  /**
   * Return the "actual" type from a parameterized type. For example, if this <code>JavaClass</code>
   * represents <code>List&lt;Employee</code>, this method will return the <code>Employee</code>
   * <code>JavaClass</code>.
   *
   * @return a <code>Collection</code> containing the actual type's <code>JavaClass</code>.
   */
  public Collection<JavaClass> getActualTypeArguments() {
    Object jType = null;
    if (this.javaType != null) {
      jType = this.javaType;
    } else {
      try {
        Class<?> jTypeClass = PrivilegedAccessHelper.getClassForName(this.javaName);
        jType = PrivilegedAccessHelper.newInstanceFromClass(jTypeClass);
      } catch (Exception e) {
        return new ArrayList<JavaClass>();
      }
    }

    ArrayList<JavaClass> argCollection = new ArrayList<JavaClass>();
    if (jType instanceof ParameterizedType) {
      ParameterizedType pType = (ParameterizedType) jType;
      Type[] params = pType.getActualTypeArguments();
      for (Type type : params) {
        if (type instanceof ParameterizedType) {
          ParameterizedType pt = (ParameterizedType) type;
          argCollection.add(this.javaModel.getClass(pt.getRawType().getClass()));
        } else if (type instanceof WildcardType) {
          Type[] upperTypes = ((WildcardType) type).getUpperBounds();
          if (upperTypes.length > 0) {
            Type upperType = upperTypes[0];
            if (upperType instanceof Class<?>) {
              argCollection.add(this.javaModel.getClass(upperType.getClass()));
            }
          }
        } else if (type instanceof Class<?>) {
          argCollection.add(this.javaModel.getClass(type.getClass()));
        } else if (type instanceof GenericArrayType) {
          Class<?> genericTypeClass =
              (Class<?>) ((GenericArrayType) type).getGenericComponentType();
          genericTypeClass = java.lang.reflect.Array.newInstance(genericTypeClass, 0).getClass();
          argCollection.add(this.javaModel.getClass(genericTypeClass.getClass()));
        }
      }
    }
    return argCollection;
  }
Ejemplo n.º 17
0
 private static boolean isAssignableFrom(Class<?> aClass, Type aType) {
   if (aType == null) {
     return false;
   }
   if (aType instanceof Class<?>) {
     return aClass.isAssignableFrom((Class<?>) aType);
   } else if (aType instanceof ParameterizedType) {
     return aClass.isAssignableFrom((Class<?>) ((ParameterizedType) aType).getRawType());
   } else {
     throw new UnsupportedOperationException("aType=" + aType.getClass().getName());
   }
 }
Ejemplo n.º 18
0
    Foo() {
      Logger logger = Logger.getLogger(getClass());

      Type t = TypeResolver.resolveInClass(Foo.class, Foo.class);
      logger.debug("........" + t.getClass());
      Field field = null;
      try {
        field = Foo.class.getDeclaredField("var");
      } catch (NoSuchFieldException e) {
        e.printStackTrace();
      }
      logger.debug(field.getType()); // class java.lang.String.
    }
Ejemplo n.º 19
0
 public Type narrow(Type aType, Class<?> targetType) {
   if (aType == null) {
     return null;
   }
   aType = tryResolve(aType);
   if (aType instanceof Class<?>) {
     return (Class<?>) aType;
   } else if (aType instanceof ParameterizedType) {
     return ((ParameterizedType) aType).getRawType();
   } else if (aType instanceof TypeVariable<?> || aType instanceof WildcardType) {
     Type[] bounds;
     if (aType instanceof WildcardType) {
       bounds = ((WildcardType) aType).getUpperBounds();
     } else {
       bounds = ((TypeVariable<?>) aType).getBounds();
     }
     Class<?> result = null;
     for (Type bound : bounds) {
       if (bound instanceof TypeVariable<?>) {
         Type resolvedBound = tryResolve((TypeVariable<?>) bound);
         if (resolvedBound != null) {
           bound = resolvedBound;
         }
       }
       bound = narrow(bound, targetType);
       if (bound instanceof Class<?>) {
         Class<?> cls = (Class<?>) bound;
         if (targetType != null) {
           if (targetType.isAssignableFrom(cls)) {
             if (result == null || (result != null && result.isAssignableFrom(cls))) {
               result = cls;
             }
           }
         } else {
           if (result == null || result.isAssignableFrom(cls)) {
             result = cls;
           }
         }
       }
     }
     if (result != null) {
       return result;
     } else {
       return aType;
     }
   } else {
     throw new IllegalStateException("Not Supported: " + aType.getClass());
   }
 }
  /**
   * Create an new instance of {@link GenericMetadataSupport} inferred from a {@link Type}.
   *
   * <p>At the moment <code>type</code> can only be a {@link Class} or a {@link ParameterizedType},
   * otherwise it'll throw a {@link MockitoException}.
   *
   * @param type The class from which the {@link GenericMetadataSupport} should be built.
   * @return The new {@link GenericMetadataSupport}.
   * @throws MockitoException Raised if type is not a {@link Class} or a {@link ParameterizedType}.
   */
  public static GenericMetadataSupport inferFrom(Type type) {
    Checks.checkNotNull(type, "type");
    if (type instanceof Class) {
      return new FromClassGenericMetadataSupport((Class<?>) type);
    }
    if (type instanceof ParameterizedType) {
      return new FromParameterizedTypeGenericMetadataSupport((ParameterizedType) type);
    }

    throw new MockitoException(
        "Type meta-data for this Type ("
            + type.getClass().getCanonicalName()
            + ") is not supported : "
            + type);
  }
Ejemplo n.º 21
0
 private ClassNode configureType(Type type) {
   if (type instanceof WildcardType) {
     return configureWildcardType((WildcardType) type);
   } else if (type instanceof ParameterizedType) {
     return configureParameterizedType((ParameterizedType) type);
   } else if (type instanceof GenericArrayType) {
     return configureGenericArray((GenericArrayType) type);
   } else if (type instanceof TypeVariable) {
     return configureTypeVariableReference((TypeVariable) type);
   } else if (type instanceof Class) {
     return configureClass((Class) type);
   } else {
     throw new GroovyBugError("unknown type: " + type + " := " + type.getClass());
   }
 }
Ejemplo n.º 22
0
  private static AssertionError buildUnexpectedTypeError(Type token, Class<?>... expected) {

    // Build exception message
    StringBuilder exceptionMessage = new StringBuilder("Unexpected type. Expected one of: ");
    for (Class<?> clazz : expected) {
      exceptionMessage.append(clazz.getName()).append(", ");
    }
    exceptionMessage
        .append("but got: ")
        .append(token.getClass().getName())
        .append(", for type token: ")
        .append(token.toString())
        .append('.');

    return new AssertionError(exceptionMessage.toString());
  }
Ejemplo n.º 23
0
 private Class<?> getClassFromGenericArgument(java.lang.reflect.Type type) {
   if (type instanceof Class) {
     return (Class) type;
   } else if (type instanceof TypeVariable) {
     final java.lang.reflect.Type upperBound = ((TypeVariable) type).getBounds()[0];
     return getClassFromGenericArgument(upperBound);
   } else if (type instanceof ParameterizedType) {
     final java.lang.reflect.Type rawType = ((ParameterizedType) type).getRawType();
     return getClassFromGenericArgument(rawType);
   } else {
     throw new AssertionFailure(
         "Fail to process type argument in a generic declaration. Member : "
             + getMemberDescription()
             + " Type: "
             + type.getClass());
   }
 }
 @SuppressWarnings("unchecked")
 private static <T> Class<T> typeOf(Task<T> task) {
   Class<?> taskType = task.getClass();
   while (taskType != Object.class) {
     for (Type type : taskType.getGenericInterfaces()) {
       if (type instanceof ParameterizedType) {
         ParameterizedType paramType = (ParameterizedType) type;
         if (paramType.getRawType() == Task.class) {
           Type param = paramType.getActualTypeArguments()[0];
           if (param.getClass() == Class.class) return (Class<T>) param;
         }
       }
     }
     taskType = taskType.getSuperclass();
   }
   return null;
 }
Ejemplo n.º 25
0
 private ClassNode configureType(Type type) {
   if (type instanceof WildcardType) {
     return configureWildcardType((WildcardType) type);
   } else if (type instanceof ParameterizedType) {
     return configureParameterizedType((ParameterizedType) type);
   } else if (type instanceof GenericArrayType) {
     return configureGenericArray((GenericArrayType) type);
   } else if (type instanceof TypeVariable) {
     return configureTypeVariableReference(((TypeVariable) type).getName());
   } else if (type instanceof Class) {
     return configureClass((Class) type);
   } else if (type == null) {
     throw new GroovyBugError(
         "Type is null. Most probably you let a transform reuse existing ClassNodes with generics information, that is now used in a wrong context.");
   } else {
     throw new GroovyBugError("unknown type: " + type + " := " + type.getClass());
   }
 }
Ejemplo n.º 26
0
  private static GenericType getGenericType(VariableMapping currentMapping, Type type) {
    // try to resolve type
    if (type == null) {
      throw new IllegalArgumentException("Type must not be null!");
    }

    if (type instanceof ParameterizedType) {
      ParameterizedType parameterizedType = (ParameterizedType) type;
      currentMapping = new VariableMapping(currentMapping, parameterizedType);
      // e.g. <X1, X2 extends Number> => <String, Integer>
      return new GenericType(currentMapping, parameterizedType);
    } else if (type instanceof Class<?>) {
      return new GenericType(currentMapping, (Class) type);
    } else if (type instanceof TypeVariable<?>) {
      return new GenericType(currentMapping, (TypeVariable<?>) type);
    } else {
      throw new IllegalStateException("Type not supported so far: " + type.getClass().getName());
    }
  }
Ejemplo n.º 27
0
 /**
  * {@code type}の種類でメソッドの再束縛を行い、該当する{@code visit*}メソッドを起動する。
  *
  * <p>このメソッドが識別可能な型は次のとおりである。
  *
  * <ul>
  *   <li>{@link Class} - {@link #visitClass(Class, Object) visitClass(type, context)}
  *   <li>{@link GenericArrayType} - {@link #visitGenericArrayType(GenericArrayType, Object)
  *       visitGenericArrayType(type, context)}
  *   <li>{@link ParameterizedType} - {@link #visitParameterizedType(ParameterizedType, Object)
  *       visitParameterizedType(type, context)}
  *   <li>{@link TypeVariable} - {@link #visitTypeVariable(TypeVariable, Object)
  *       visitTypeVariable(type, context)}
  *   <li>{@link WildcardType} - {@link #visitWildcardType(WildcardType, Object)
  *       visitWildcardType(type, context)}
  * </ul>
  *
  * <p>上記のいずれでもない場合、この呼び出しは失敗する。 また、上記のうち複数のサブタイプであるようなオブジェクトを{@code type}に指定した場合、 実際に呼び出される{@code
  * visit*}メソッドは保証されない。
  *
  * @param type メソッドの再束縛をする型
  * @param context コンテキストオブジェクト(省略可)
  * @return 再束縛された{@code visit*}の実行結果
  * @throws E 再束縛された{@code visit*}の実行中に例外が発生した場合
  * @throws IllegalArgumentException 引数{@code type}が {@link Class}, {@link GenericArrayType},
  *     {@link ParameterizedType}, {@link TypeVariable}, {@link WildcardType} のいずれでもない場合
  * @throws IllegalArgumentException 引数に{@code null}が含まれる場合
  */
 public final R dispatch(Type type, C context) throws E {
   if (type == null) {
     throw new IllegalArgumentException("type must not be null"); // $NON-NLS-1$
   }
   if (type instanceof Class<?>) {
     return visitClass((Class<?>) type, context);
   } else if (type instanceof GenericArrayType) {
     return visitGenericArrayType((GenericArrayType) type, context);
   } else if (type instanceof ParameterizedType) {
     return visitParameterizedType((ParameterizedType) type, context);
   } else if (type instanceof TypeVariable<?>) {
     return visitTypeVariable((TypeVariable<?>) type, context);
   } else if (type instanceof WildcardType) {
     return visitWildcardType((WildcardType) type, context);
   } else {
     throw new IllegalArgumentException(
         MessageFormat.format(
             "Unknown Type Kind: {0} ({1})", type, type.getClass().getSimpleName()));
   }
 }
Ejemplo n.º 28
0
  public static Class<?> getActualType(Type genericType, final int pos) {

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

      final Class<?> cls = (Class<?>) genericType;
      return cls.isArray() ? cls.getComponentType() : cls;
    }
    final ParameterizedType paramType = (ParameterizedType) genericType;
    final Type t = getType(paramType.getActualTypeArguments(), pos);
    return t instanceof Class ? (Class<?>) t : getActualType(t, pos);
  }
Ejemplo n.º 29
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);
      return (Class<?>) rawType;

    } else if (type instanceof GenericArrayType) {
      Type componentType = ((GenericArrayType) type).getGenericComponentType();
      return Array.newInstance(getRawType(componentType), 0).getClass();

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

    } else if (type instanceof WildcardType) {
      return getRawType(((WildcardType) type).getUpperBounds()[0]);

    } else {
      String className = type == null ? "null" : type.getClass().getName();
      throw new IllegalArgumentException(
          "Expected a Class, ParameterizedType, or "
              + "GenericArrayType, but <"
              + type
              + "> is of type "
              + className);
    }
  }
  public void attachTypes(ApplicationDescription introspector) {

    // If we managed to get an introspector then lets go back an update the parameters

    if (introspector != null) {

      for (TypeCallbackPair pair : nameCallbacks) {

        // There is a method on the RI version that works with just
        // the class name; but using the introspector for the moment
        // as it leads to cleaner code
        Class<?> parameterClass = pair.genericType.getRawType();

        // Fix those specific generic types
        if (SPECIAL_GENERIC_TYPES.contains(parameterClass)) {
          Type type = pair.genericType.getType();

          if (ParameterizedType.class.isAssignableFrom(type.getClass())
              && Class.class.isAssignableFrom(
                  ((ParameterizedType) type).getActualTypeArguments()[0].getClass())) {
            parameterClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[0];
          } else {
            // Works around JERSEY-830
            LOGGER.fine("Couldn't find JAX-B element due to nested parameterized type " + type);
            return;
          }
        }

        QName name = introspector.resolve(parameterClass);

        if (name != null) {
          pair.nameCallbackSetter.setName(name);
        } else {
          LOGGER.fine("Couldn't find JAX-B element for class " + parameterClass.getName());
        }
      }
    }
  }