Java 类java.lang.reflect.ParameterizedType 实例源码

项目:letv    文件:C$Gson$Types.java   
public static Type canonicalize(Type type) {
    if (type instanceof Class) {
        Class<?> c = (Class) type;
        return c.isArray() ? new GenericArrayTypeImpl(C$Gson$Types.canonicalize(c.getComponentType())) : c;
    } else if (type instanceof ParameterizedType) {
        ParameterizedType p = (ParameterizedType) type;
        return new ParameterizedTypeImpl(p.getOwnerType(), p.getRawType(), p.getActualTypeArguments());
    } else if (type instanceof GenericArrayType) {
        return new GenericArrayTypeImpl(((GenericArrayType) type).getGenericComponentType());
    } else {
        if (!(type instanceof WildcardType)) {
            return type;
        }
        WildcardType w = (WildcardType) type;
        return new WildcardTypeImpl(w.getUpperBounds(), w.getLowerBounds());
    }
}
项目:lams    文件:$Gson$Types.java   
/**
 * Returns a type that is functionally equal but not necessarily equal
 * according to {@link Object#equals(Object) Object.equals()}. The returned
 * type is {@link java.io.Serializable}.
 */
public static Type canonicalize(Type type) {
  if (type instanceof Class) {
    Class<?> c = (Class<?>) type;
    return c.isArray() ? new GenericArrayTypeImpl(canonicalize(c.getComponentType())) : c;

  } else if (type instanceof ParameterizedType) {
    ParameterizedType p = (ParameterizedType) type;
    return new ParameterizedTypeImpl(p.getOwnerType(),
        p.getRawType(), p.getActualTypeArguments());

  } else if (type instanceof GenericArrayType) {
    GenericArrayType g = (GenericArrayType) type;
    return new GenericArrayTypeImpl(g.getGenericComponentType());

  } else if (type instanceof WildcardType) {
    WildcardType w = (WildcardType) type;
    return new WildcardTypeImpl(w.getUpperBounds(), w.getLowerBounds());

  } else {
    // type is either serializable as-is or unsupported
    return type;
  }
}
项目:jsouplib    文件:TypeLiteral.java   
private static String formatTypeWithoutSpecialCharacter(Type type) {
    if (type instanceof Class) {
        Class clazz = (Class) type;
        return clazz.getCanonicalName();
    }
    if (type instanceof ParameterizedType) {
        ParameterizedType pType = (ParameterizedType) type;
        String typeName = formatTypeWithoutSpecialCharacter(pType.getRawType());
        for (Type typeArg : pType.getActualTypeArguments()) {
            typeName += "_";
            typeName += formatTypeWithoutSpecialCharacter(typeArg);
        }
        return typeName;
    }
    if (type instanceof GenericArrayType) {
        GenericArrayType gaType = (GenericArrayType) type;
        return formatTypeWithoutSpecialCharacter(gaType.getGenericComponentType()) + "_array";
    }
    throw new AJsoupReaderException("unsupported type: " + type + ", of class " + type.getClass());
}
项目:openjdk-jdk10    文件:DefaultMXBeanMappingFactory.java   
CollectionMapping(Type targetType,
                  ArrayType<?> openArrayType,
                  Class<?> openArrayClass,
                  MXBeanMapping elementMapping) {
    super(targetType, openArrayType);
    this.elementMapping = elementMapping;

    /* Determine the concrete class to be used when converting
       back to this Java type.  We convert all Lists to ArrayList
       and all Sets to TreeSet.  (TreeSet because it is a SortedSet,
       so works for both Set and SortedSet.)  */
    Type raw = ((ParameterizedType) targetType).getRawType();
    Class<?> c = (Class<?>) raw;
    final Class<?> collC;
    if (c == List.class)
        collC = ArrayList.class;
    else if (c == Set.class)
        collC = HashSet.class;
    else if (c == SortedSet.class)
        collC = TreeSet.class;
    else { // can't happen
        assert(false);
        collC = null;
    }
    collectionClass = Util.cast(collC);
}
项目:aws-sdk-java-v2    文件:ConversionSchemas.java   
private ArgumentMarshaller getObjectToMapMarshaller(Type type) {
    Type localType = type;
    if (localType instanceof ParameterizedType) {
        localType = ((ParameterizedType) localType).getRawType();
    }

    if (!(localType instanceof Class)) {
        throw new DynamoDbMappingException(
                "Cannot convert " + type + " to a class");
    }

    Class<?> clazz = (Class<?>) localType;
    if (StandardAnnotationMaps.of(clazz).attributeType() != DynamoDbAttributeType.M) {
        throw new DynamoDbMappingException(
                "Cannot marshall type " + type
                + " without a custom marshaler or @DynamoDBDocument "
                + "annotation.");
    }

    return new ObjectToMapMarshaller(this);
}
项目:SDI    文件:ServiceBuilder.java   
private Class<?> getCreatedClass(Creator<?> creator) {
    String typeName = ((ParameterizedType) creator.getClass()
                                                  .getGenericSuperclass()).getActualTypeArguments()[0]
            .getTypeName();
    int typeParametersIndex = typeName.indexOf('<');

    if (typeParametersIndex != -1) {
        typeName = typeName.substring(0, typeParametersIndex);
    }

    Class<?> clazz;

    try {
        clazz = Class.forName(typeName);
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException("Can not find a Class for '" + typeName + "'.", e);
    }

    return clazz;
}
项目:googles-monorepo-demo    文件:TypeTokenTest.java   
public void testGetSubtype_recursiveTypeBoundInSubtypeTranslatedAsIs() {
  class BaseWithTypeVar<T> {}
  class Outer<O> {
    class Sub<X> extends BaseWithTypeVar<List<X>> {}
    class Sub2<Y extends Sub2<Y>> extends BaseWithTypeVar<List<Y>> {}
  }
  ParameterizedType subtype = (ParameterizedType) new TypeToken<BaseWithTypeVar<List<?>>>() {}
          .getSubtype(Outer.Sub.class)
          .getType();
  assertEquals(Outer.Sub.class, subtype.getRawType());
  assertThat(subtype.getActualTypeArguments()[0]).isInstanceOf(WildcardType.class);
  ParameterizedType owner = (ParameterizedType) subtype.getOwnerType();
  assertEquals(Outer.class, owner.getRawType());
  // This returns a strange ? extends Sub2<Y> type, which isn't ideal.
  TypeToken<?> unused = new TypeToken<BaseWithTypeVar<List<?>>>() {}.getSubtype(Outer.Sub2.class);
}
项目:firebase-admin-java    文件:CustomClassMapper.java   
/**
 * Converts a standard library Java representation of JSON data to an object of the class provided
 * through the GenericTypeIndicator
 *
 * @param object The representation of the JSON data
 * @param typeIndicator The indicator providing class of the object to convert to
 * @return The POJO object.
 */
public static <T> T convertToCustomClass(Object object, GenericTypeIndicator<T> typeIndicator) {
  Class<?> clazz = typeIndicator.getClass();
  Type genericTypeIndicatorType = clazz.getGenericSuperclass();
  if (genericTypeIndicatorType instanceof ParameterizedType) {
    ParameterizedType parameterizedType = (ParameterizedType) genericTypeIndicatorType;
    if (!parameterizedType.getRawType().equals(GenericTypeIndicator.class)) {
      throw new DatabaseException(
          "Not a direct subclass of GenericTypeIndicator: " + genericTypeIndicatorType);
    }
    // We are guaranteed to have exactly one type parameter
    Type type = parameterizedType.getActualTypeArguments()[0];
    return deserializeToType(object, type);
  } else {
    throw new DatabaseException(
        "Not a direct subclass of GenericTypeIndicator: " + genericTypeIndicatorType);
  }
}
项目:xm-ms-entity    文件:FixedDefaultJsonUnmarshaller.java   
private <T> void setField(final T resultObject, final Field field, final Object unmarshalledValue)
    throws IllegalAccessException, IOException {

    final Class<?> fieldType = field.getType();
    final Type genericType = field.getGenericType();

    if (fieldType.isPrimitive()) {
        reflectionUtil.setField(resultObject, field, unmarshalledValue);

    } else if (genericType instanceof ParameterizedType) {
        final Class<?>[] actualTypeArguments = reflectionUtil.geClassArgumentsFromGeneric(genericType);

        final JavaType typedField;
        if (actualTypeArguments.length == 1) {
            typedField = objectMapper.getTypeFactory().constructParametricType(fieldType, actualTypeArguments[0]);
        } else {
            typedField = objectMapper.getTypeFactory()
                .constructMapLikeType(fieldType, actualTypeArguments[0], actualTypeArguments[1]);
        }

        reflectionUtil.setField(resultObject, field, objectMapper.convertValue(unmarshalledValue, typedField));

    } else {
        reflectionUtil.setField(resultObject, field, objectMapper.convertValue(unmarshalledValue, fieldType));
    }
}
项目:odoo-work    文件:$Gson$Types.java   
static Type resolveTypeVariable(Type context, Class<?> contextRawType, TypeVariable<?> unknown) {
  Class<?> declaredByRaw = declaringClassOf(unknown);

  // we can't reduce this further
  if (declaredByRaw == null) {
    return unknown;
  }

  Type declaredBy = getGenericSupertype(context, contextRawType, declaredByRaw);
  if (declaredBy instanceof ParameterizedType) {
    int index = indexOf(declaredByRaw.getTypeParameters(), unknown);
    return ((ParameterizedType) declaredBy).getActualTypeArguments()[index];
  }

  return unknown;
}
项目:lams    文件:$Gson$Types.java   
/**
 * Returns a two element array containing this map's key and value types in
 * positions 0 and 1 respectively.
 */
public static Type[] getMapKeyAndValueTypes(Type context, Class<?> contextRawType) {
  /*
   * Work around a problem with the declaration of java.util.Properties. That
   * class should extend Hashtable<String, String>, but it's declared to
   * extend Hashtable<Object, Object>.
   */
  if (context == Properties.class) {
    return new Type[] { String.class, String.class }; // TODO: test subclasses of Properties!
  }

  Type mapType = getSupertype(context, contextRawType, Map.class);
  // TODO: strip wildcards?
  if (mapType instanceof ParameterizedType) {
    ParameterizedType mapParameterizedType = (ParameterizedType) mapType;
    return mapParameterizedType.getActualTypeArguments();
  }
  return new Type[] { Object.class, Object.class };
}
项目:lazycat    文件:Util.java   
private static TypeResult getTypeParameter(Class<?> clazz, Type argType) {
    if (argType instanceof Class<?>) {
        return new TypeResult((Class<?>) argType, -1, 0);
    } else if (argType instanceof ParameterizedType) {
        return new TypeResult((Class<?>) ((ParameterizedType) argType).getRawType(), -1, 0);
    } else if (argType instanceof GenericArrayType) {
        Type arrayElementType = ((GenericArrayType) argType).getGenericComponentType();
        TypeResult result = getTypeParameter(clazz, arrayElementType);
        result.incrementDimension(1);
        return result;
    } else {
        TypeVariable<?>[] tvs = clazz.getTypeParameters();
        for (int i = 0; i < tvs.length; i++) {
            if (tvs[i].equals(argType)) {
                return new TypeResult(null, i, 0);
            }
        }
        return null;
    }
}
项目:liteBatch    文件:Reflections.java   
/**
 * 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
 * 如无法找到, 返回Object.class.
 * 
 * 如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
 */
public static Class getClassGenricType(final Class clazz, final int index) {

    Type genType = clazz.getGenericSuperclass();

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

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

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

    return (Class) params[index];
}
项目:jsf-sdk    文件:ArrayListTypeFieldDeserializer.java   
public ArrayListTypeFieldDeserializer(ParserConfig mapping, Class<?> clazz, FieldInfo fieldInfo){
    super(clazz, fieldInfo);

    Type fieldType = fieldInfo.fieldType;
    if (fieldType instanceof ParameterizedType) {
        Type argType = ((ParameterizedType) fieldInfo.fieldType).getActualTypeArguments()[0];
        if (argType instanceof WildcardType) {
            WildcardType wildcardType = (WildcardType) argType;
            Type[] upperBounds = wildcardType.getUpperBounds();
            if (upperBounds.length == 1) {
                argType = upperBounds[0];
            }
        }
        this.itemType = argType;
    } else {
        this.itemType = Object.class;
    }
}
项目:SlimAdapter    文件:SlimAdapter.java   
private boolean isTypeMatch(Type type, Type targetType) {
    if (type instanceof Class && targetType instanceof Class) {
        if (((Class) type).isAssignableFrom((Class) targetType)) {
            return true;
        }
    } else if (type instanceof ParameterizedType && targetType instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        ParameterizedType parameterizedTargetType = (ParameterizedType) targetType;
        if (isTypeMatch(parameterizedType.getRawType(), ((ParameterizedType) targetType).getRawType())) {
            Type[] types = parameterizedType.getActualTypeArguments();
            Type[] targetTypes = parameterizedTargetType.getActualTypeArguments();
            if (types == null || targetTypes == null || types.length != targetTypes.length) {
                return false;
            }
            int len = types.length;
            for (int i = 0; i < len; i++) {
                if (!isTypeMatch(types[i], targetTypes[i])) {
                    return false;
                }
            }
            return true;
        }
    }
    return false;
}
项目:odoo-work    文件:$Gson$Types.java   
/**
 * Returns a two element array containing this map's key and value types in
 * positions 0 and 1 respectively.
 */
public static Type[] getMapKeyAndValueTypes(Type context, Class<?> contextRawType) {
  /*
   * Work around a problem with the declaration of java.util.Properties. That
   * class should extend Hashtable<String, String>, but it's declared to
   * extend Hashtable<Object, Object>.
   */
  if (context == Properties.class) {
    return new Type[] { String.class, String.class }; // TODO: test subclasses of Properties!
  }

  Type mapType = getSupertype(context, contextRawType, Map.class);
  // TODO: strip wildcards?
  if (mapType instanceof ParameterizedType) {
    ParameterizedType mapParameterizedType = (ParameterizedType) mapType;
    return mapParameterizedType.getActualTypeArguments();
  }
  return new Type[] { Object.class, Object.class };
}
项目:OpenJSharp    文件:RuntimeModeler.java   
private Class getAsyncReturnType(Method method, Class returnType) {
    if(Response.class.isAssignableFrom(returnType)){
        Type ret = method.getGenericReturnType();
        return (Class) Utils.REFLECTION_NAVIGATOR.erasure(((ParameterizedType)ret).getActualTypeArguments()[0]);
    }else{
        Type[] types = method.getGenericParameterTypes();
        Class[] params = method.getParameterTypes();
        int i = 0;
        for(Class cls : params){
            if(AsyncHandler.class.isAssignableFrom(cls)){
                return (Class) Utils.REFLECTION_NAVIGATOR.erasure(((ParameterizedType)types[i]).getActualTypeArguments()[0]);
            }
            i++;
        }
    }
    return returnType;
}
项目:spring-grow    文件:ConversionUtility.java   
public static Class<?> getFieldType(Class<?> persistentClass, String name) throws NoSuchFieldException {
   String[] fields = StringUtils.delimitedListToStringArray(name, ".");
   Class<?> t;

   t = persistentClass.getDeclaredField(fields[0]).getType();

   if (Collection.class.isAssignableFrom(t)) {
      Field collectionField = persistentClass.getDeclaredField(fields[0]);
      ParameterizedType collectionType = (ParameterizedType) collectionField.getGenericType();
      t = (Class<?>) collectionType.getActualTypeArguments()[0];
   }
   if (fields.length == 1) {
      return t;
   } else {
      return getFieldType((Class<?>) t, name.substring(name.indexOf(".") + 1));
   }
}
项目:Android-Router    文件:ReflectTool.java   
@SuppressWarnings("all")
public static String getFieldTypeWithGeneric(Field f) {
    Class fieldType = f.getType();
    //TODO Anonymous Inner Class Cant be find By Class.fromName,but getName could.
    String type = fieldType.getCanonicalName();
    if (fieldType.isAssignableFrom(List.class)) {
        try {
            ParameterizedType pt = (ParameterizedType) f.getGenericType();
            return pt.toString();
        } catch (ClassCastException ignored) {
        }
    }
    return type;
}
项目:GitHub    文件:NewsCallback.java   
/**
 * 这里的数据解析是根据 http://gank.io/api/data/Android/10/1 返回的数据来写的
 * 实际使用中,自己服务器返回的数据格式和上面网站肯定不一样,所以以下是参考代码,根据实际情况自己改写
 */
@Override
public T convertResponse(Response response) throws Throwable {
    //以下代码是通过泛型解析实际参数,泛型必须传
    Type genType = getClass().getGenericSuperclass();
    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
    Type type = params[0];
    if (!(type instanceof ParameterizedType)) throw new IllegalStateException("没有填写泛型参数");

    JsonReader jsonReader = new JsonReader(response.body().charStream());
    Type rawType = ((ParameterizedType) type).getRawType();
    if (rawType == GankResponse.class) {
        GankResponse gankResponse = Convert.fromJson(jsonReader, type);
        if (!gankResponse.error) {
            response.close();
            //noinspection unchecked
            return (T) gankResponse;
        } else {
            response.close();
            throw new IllegalStateException("服务端接口错误");
        }
    } else {
        response.close();
        throw new IllegalStateException("基类错误无法解析!");
    }
}
项目:jsouplib    文件:AnalysisDecoder.java   
/**
 * 创建解析器
 *
 * @param cacheKey
 * @param type
 * @param annotations
 * @return
 */
private static Decoder gen(String cacheKey, Type type, Annotation[] annotations) {
    Decoder decoder = getDecoder(cacheKey);
    if (decoder != null) {
        return decoder;
    }

    type = ReflectKit.chooseImpl(type);

    Type[] typeArgs = new Type[0];
    Class clazz;
    if (type instanceof ParameterizedType) {
        ParameterizedType pType = (ParameterizedType) type;
        clazz = (Class) pType.getRawType();
        typeArgs = pType.getActualTypeArguments();
    } else {
        clazz = (Class) type;
    }
    decoder = NATIVE_DECODERS.get(clazz);//基本数据类型
    if (decoder != null) {
        return decoder;
    }
    decoder = registerDecoder.get(clazz); //自定义的解析器
    if (decoder == null) {
        decoder = ReflectionDecoderFactory.create(clazz, annotations, typeArgs);  //注解解析器
    }
    cacheDecoder(cacheKey, decoder);
    return decoder;
}
项目:guava-mock    文件:Types.java   
private static ClassOwnership detectJvmBehavior() {
  class LocalClass<T> {}
  Class<?> subclass = new LocalClass<String>() {}.getClass();
  ParameterizedType parameterizedType = (ParameterizedType) subclass.getGenericSuperclass();
  for (ClassOwnership behavior : ClassOwnership.values()) {
    if (behavior.getOwnerType(LocalClass.class) == parameterizedType.getOwnerType()) {
      return behavior;
    }
  }
  throw new AssertionError();
}
项目:booter-injector    文件:Key.java   
/**
 * Create key for single method/constructor parameter.
 *
 * @param parameter
 *          Parameter to build key for.
 * @return Created key.
 */
public static Key of(Parameter parameter) {
    Annotation[] annotations = parameter.getAnnotations();

    if (!parameter.getType().isAssignableFrom(Supplier.class)) {
        return new Key(parameter.getParameterizedType(), false,
                       parameter.getType(), findBindingAnnotation(annotations));
    }

    Type type = parameter.getParameterizedType();

    if (type instanceof ParameterizedType) {
        Type[] args = ((ParameterizedType) type).getActualTypeArguments();

        if (args.length > 0 && args[0] instanceof Class) {
            return Key.of(args[0], true, annotations);
        }
    }

    throw new InjectorException("Unable to determine parameter type for " + parameter);
}
项目:BIMplatform    文件:ReflectionUtils.java   
/** 
 * 通过反射, 获得Class定义中声明的父类的泛型参数的类型. 
 * 如无法找到, 返回Object.class. 
 *  
 * 如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 instanceof ParameterizedType)) {  
        logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");  
        return Object.class;  
    }  

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

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

    return (Class) params[index];  
}
项目:spring-boot-elastcsearch-example    文件:ReflectUtils.java   
/**
 * 得到指定类型的指定位置的泛型实参
 * @param clazz
 * @param index
 * @param <T>
 * @return
 */
public static <T> Class<T> findParameterizedType(Class<?> clazz, int index) {
    Type parameterizedType = clazz.getGenericSuperclass();
    //CGLUB subclass target object(泛型在父类上)
    if (!(parameterizedType instanceof ParameterizedType)) {
        parameterizedType = clazz.getSuperclass().getGenericSuperclass();
    }
    if (!(parameterizedType instanceof ParameterizedType)) {
        return null;
    }
    Type[] actualTypeArguments = ((ParameterizedType) parameterizedType).getActualTypeArguments();
    if (actualTypeArguments == null || actualTypeArguments.length == 0) {
        return null;
    }
    return (Class<T>) actualTypeArguments[0];
}
项目:DUnit    文件:InitMethodUtil.java   
/**
 * 创建init方法,用于数据初始化
 *
 * @param methodName        方法名
 * @param genericTypesClass ArrayList泛型的类型
 * @param gsonDataString    ArrayList被Gson转换出的字符串
 * @param modelListVariableName      GsonData被还原后的临时变量名
 * @return 初始化方法的构造器
 */
public static MethodSpec.Builder createInitMethodSpecBuilder(String methodName, Class genericTypesClass, String gsonDataString, String modelListVariableName) {
    String tmpStr;

    //Override注解
    AnnotationSpec annotation = createOverrideAnnotation();

    //return type,返回值
    ParameterizedType returnType = GenericTypesUtil.type(ArrayList.class, genericTypesClass);

    //protected ArrayList<DUnitModel> initUnitModels(),函数声明
    MethodSpec.Builder initMethodBuilder = MethodSpec
            .methodBuilder(methodName)
            .addModifiers(Modifier.PROTECTED)
            .addAnnotation(annotation)
            .returns(returnType);

    //Gson gson = new Gson();
    initMethodBuilder.addStatement("$T gson = new $T()", Gson.class, Gson.class);
    //ParameterizedType type = GenericTypesUtil.type(ArrayList.class,DUnitModel.class);
    initMethodBuilder.addStatement("$T type = $T.type($T.class,$T.class)", ParameterizedType.class, GenericTypesUtil.class, ArrayList.class, genericTypesClass);
    //ArrayList<DUnitModel> unitModels = gson.fromJson(unitModelsString_c,type);
    tmpStr = String.format("$T<$T> %s = gson.fromJson($S,type)", modelListVariableName);
    initMethodBuilder.addStatement(tmpStr, ArrayList.class, genericTypesClass, gsonDataString);
    return initMethodBuilder;
}
项目:gitplex-mit    文件:ReflectionUtils.java   
public static Class<?> getMapValueType(Type type) {
    if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType)type;
        Type rawType = parameterizedType.getRawType();

        if (rawType instanceof Class<?>) {
            Class<?> rawClazz = (Class<?>) rawType;
            if (Map.class.isAssignableFrom(rawClazz)) {
                Type valueType = parameterizedType.getActualTypeArguments()[1];
                if (valueType instanceof Class<?>) {
                    return (Class<?>) valueType;
                } else if (valueType instanceof ParameterizedType) {
                    return (Class<?>) ((ParameterizedType)valueType).getRawType();
                }
            }
        }
    }
    return null;
}
项目:util    文件:ClassUtil.java   
/**
 * 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
 * 
 * 注意泛型必须定义在父类处. 这是唯一可以通过反射从泛型获得Class实例的地方.
 * 
 * 如无法找到, 返回Object.class.
 * 
 * 如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 getClassGenricType(final Class clazz, final int index) {

    Type genType = clazz.getGenericSuperclass();

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

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

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

    return (Class) params[index];
}
项目:dtmlibs    文件:Field.java   
@Nullable
private Class determineCollectionType(@NotNull Type type) {
    if (Collection.class.isAssignableFrom(getType())) {
        Type collectionType = GenericTypeReflector.getExactSuperType(type, Collection.class);
        if (collectionType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) collectionType;
            collectionType = parameterizedType.getActualTypeArguments()[0];
            if (collectionType instanceof Class) {
                return (Class) collectionType;
            }
        }
        if (collectionType instanceof WildcardType) {
            return Object.class;
        }
        return GenericTypeReflector.erase(collectionType);
    }
    return null;
}
项目:stynico    文件:GsonType.java   
public static Type getSuperclassTypeParameter(Class<?> subclass) {
       Type superclass = subclass.getGenericSuperclass();
       if (superclass instanceof Class) {
           throw new RuntimeException("Missing type parameter.");
       }
       ParameterizedType parameterized = (ParameterizedType) superclass;
      // return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
    return null;
}
项目:javaide    文件:ParameterizedTypeImpl.java   
@Override
public boolean equals(Object o) {
    if (o instanceof ParameterizedType) {
        // Check that information is equivalent
        ParameterizedType that = (ParameterizedType) o;

        if (this == that)
            return true;

        Type thatOwner   = that.getOwnerType();
        Type thatRawType = that.getRawType();

        if (false) { // Debugging
            boolean ownerEquality = (ownerType == null ?
                                     thatOwner == null :
                                     ownerType.equals(thatOwner));
            boolean rawEquality = (rawType == null ?
                                   thatRawType == null :
                                   rawType.equals(thatRawType));

            boolean typeArgEquality = Arrays.equals(actualTypeArguments, // avoid clone
                                                    that.getActualTypeArguments());
            for (Type t : actualTypeArguments) {
                System.out.printf("\t\t%s%s%n", t, t.getClass());
            }

            System.out.printf("\towner %s\traw %s\ttypeArg %s%n",
                              ownerEquality, rawEquality, typeArgEquality);
            return ownerEquality && rawEquality && typeArgEquality;
        }


        return
            (ownerType == null ?
             thatOwner == null :
             ownerType.equals(thatOwner)) &&
            (rawType == null ?
             thatRawType == null :
             rawType.equals(thatRawType)) &&
            Arrays.equals(actualTypeArguments, // avoid clone
                          that.getActualTypeArguments());
    } else
        return false;
}
项目:FastBootWeixin    文件:WxUserProvider.java   
/**
 * 可能会有bug,当这个类的实现类有多个泛型时\
 * 没bug啦,改进了
 *
 * @param clazz
 * @return dummy
 */
default boolean isMatch(Class<?> clazz) {
    Type[] types = this.getClass().getGenericInterfaces();
    Class userClass = Arrays.stream(types).filter(t -> t instanceof ParameterizedType)
            .map(ParameterizedType.class::cast)
            .filter(t -> t.getRawType().equals(WxUserProvider.class))
            .findFirst().map(t -> (Class) t.getActualTypeArguments()[0])
            .orElse(null);
    if (userClass == null) {
        return false;
    }
    return clazz.isAssignableFrom(userClass);
}
项目:loom    文件:AdapterManagerImpl.java   
private Class<?> findCoreItemAttributesType(final Class<?> item) {
    Type ciaType = null;
    Class<?> ciaClass = null;
    Type currentType = item.getGenericSuperclass();
    boolean found = false;
    // null when class is Object
    while (!found && currentType != null) {
        if (currentType instanceof Class) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Found class: " + currentType.toString());
            }
            currentType = ((Class<?>) currentType).getGenericSuperclass();
        } else if (currentType instanceof ParameterizedType) {
            ciaType = ((ParameterizedType) currentType).getActualTypeArguments()[0];
            if (LOG.isDebugEnabled()) {
                LOG.debug("Found ParameterizedType: " + ciaType);
            }
            if (ciaType instanceof Class && isSubclassOfItemAttributes((Class<?>) ciaType)) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found Matching Class: " + ciaType);
                }
                ciaClass = (Class<?>) ciaType;
                found = true;
            } else {
                currentType = ((Class<?>) (((ParameterizedType) currentType).getRawType())).getGenericSuperclass();
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Found unknown: " + currentType.toString());
            }
        }

    }
    return ciaClass;
}
项目:ctsms    文件:Accessor.java   
public Class getMapValueType() {
    try {
        return (Class) ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[1];
    } catch (Exception e) {
        return Object.class;
    }
}
项目:super-volley    文件:ErrorHandlingCallAdapterFactory.java   
@Override
public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, SuperVolley volley) {
    if (getRawType(returnType) != MyCall.class) {
        return null;
    }
    if (!(returnType instanceof ParameterizedType)) {
        throw new IllegalStateException(
                "MyCall must have generic type (e.g., MyCall<ResponseBody>)");
    }
    Type responseType = getParameterUpperBound(0, (ParameterizedType) returnType);
    Executor callbackExecutor = volley.callbackExecutor();
    return new ErrorHandlingCallAdapter<>(responseType, callbackExecutor);
}
项目:HTAPBench    文件:ClassUtil.java   
/**
 * Get the generic types for the given field
 * @param field
 * @return
 */
public static List<Class<?>> getGenericTypes(Field field) {
    ArrayList<Class<?>> generic_classes = new ArrayList<Class<?>>();
    Type gtype = field.getGenericType();
    if (gtype instanceof ParameterizedType) {
        ParameterizedType ptype = (ParameterizedType)gtype;
        getGenericTypesImpl(ptype, generic_classes);
    }
    return (generic_classes);
}
项目:hy.common.base    文件:MethodReflect.java   
/**
 * 获取方法某个入参参数上的某个位置的范型Class原型
 * 
 * @param i_Method
 * @param i_ParamIndex      方法的入参参数位置
 * @param i_GenericsIndex   入参参数范型的位置
 * @return
 */
public static Class<?> getGenerics(Method i_Method ,int i_ParamIndex ,int i_GenericsIndex)
{
    try
    {
        ParameterizedType v_PType = (ParameterizedType) i_Method.getGenericParameterTypes()[i_ParamIndex];
        Type              v_Type  = v_PType.getActualTypeArguments()[i_GenericsIndex];
        return (Class<?>)v_Type;
    }
    catch (Exception exce)
    {
        return null;
    }
}
项目:s-store    文件:ClassUtil.java   
/**
 * Get the generic types for the given field
 * 
 * @param field
 * @return
 */
public static List<Class<?>> getGenericTypes(Field field) {
    ArrayList<Class<?>> generic_classes = new ArrayList<Class<?>>();
    Type gtype = field.getGenericType();
    if (gtype instanceof ParameterizedType) {
        ParameterizedType ptype = (ParameterizedType) gtype;
        getGenericTypesImpl(ptype, generic_classes);
    }
    return (generic_classes);
}
项目:saluki    文件:ReflectUtils.java   
public static Class<?> getGenericClass(Class<?> cls, int i) {
  try {
    ParameterizedType parameterizedType = ((ParameterizedType) cls.getGenericInterfaces()[0]);
    Object genericClass = parameterizedType.getActualTypeArguments()[i];
    if (genericClass instanceof ParameterizedType) { // 处理多级泛型
      return (Class<?>) ((ParameterizedType) genericClass).getRawType();
    } else if (genericClass instanceof GenericArrayType) { // 处理数组泛型
      return (Class<?>) ((GenericArrayType) genericClass).getGenericComponentType();
    } else {
      return (Class<?>) genericClass;
    }
  } catch (Throwable e) {
    throw new IllegalArgumentException(cls.getName() + " generic type undefined!", e);
  }
}
项目:Reer    文件:DefaultServiceRegistry.java   
public boolean isSatisfiedBy(Type element) {
    if (element instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) element;
        if (parameterizedType.getRawType() instanceof Class) {
            return type.isAssignableFrom((Class) parameterizedType.getRawType());
        }
    } else if (element instanceof Class) {
        Class<?> other = (Class<?>) element;
        return type.isAssignableFrom(other);
    }
    return false;
}