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

C$Gson$Types.java 文件源码 项目:letv 阅读 38 收藏 0 点赞 0 评论 0
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());
    }
}
$Gson$Types.java 文件源码 项目:lams 阅读 38 收藏 0 点赞 0 评论 0
/**
 * 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;
  }
}
TypeLiteral.java 文件源码 项目:jsouplib 阅读 47 收藏 0 点赞 0 评论 0
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());
}
DefaultMXBeanMappingFactory.java 文件源码 项目:openjdk-jdk10 阅读 48 收藏 0 点赞 0 评论 0
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);
}
ConversionSchemas.java 文件源码 项目:aws-sdk-java-v2 阅读 37 收藏 0 点赞 0 评论 0
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);
}
ServiceBuilder.java 文件源码 项目:SDI 阅读 60 收藏 0 点赞 0 评论 0
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;
}
TypeTokenTest.java 文件源码 项目:googles-monorepo-demo 阅读 49 收藏 0 点赞 0 评论 0
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);
}
CustomClassMapper.java 文件源码 项目:firebase-admin-java 阅读 52 收藏 0 点赞 0 评论 0
/**
 * 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);
  }
}
FixedDefaultJsonUnmarshaller.java 文件源码 项目:xm-ms-entity 阅读 53 收藏 0 点赞 0 评论 0
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));
    }
}
$Gson$Types.java 文件源码 项目:odoo-work 阅读 61 收藏 0 点赞 0 评论 0
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;
}
$Gson$Types.java 文件源码 项目:lams 阅读 39 收藏 0 点赞 0 评论 0
/**
 * 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 };
}
Util.java 文件源码 项目:lazycat 阅读 45 收藏 0 点赞 0 评论 0
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;
    }
}
Reflections.java 文件源码 项目:liteBatch 阅读 45 收藏 0 点赞 0 评论 0
/**
 * 通过反射, 获得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];
}
ArrayListTypeFieldDeserializer.java 文件源码 项目:jsf-sdk 阅读 62 收藏 0 点赞 0 评论 0
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.java 文件源码 项目:SlimAdapter 阅读 50 收藏 0 点赞 0 评论 0
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;
}
$Gson$Types.java 文件源码 项目:odoo-work 阅读 55 收藏 0 点赞 0 评论 0
/**
 * 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 };
}
RuntimeModeler.java 文件源码 项目:OpenJSharp 阅读 52 收藏 0 点赞 0 评论 0
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;
}
ConversionUtility.java 文件源码 项目:spring-grow 阅读 38 收藏 0 点赞 0 评论 0
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));
   }
}
ReflectTool.java 文件源码 项目:Android-Router 阅读 41 收藏 0 点赞 0 评论 0
@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;
}
NewsCallback.java 文件源码 项目:GitHub 阅读 48 收藏 0 点赞 0 评论 0
/**
 * 这里的数据解析是根据 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("基类错误无法解析!");
    }
}
AnalysisDecoder.java 文件源码 项目:jsouplib 阅读 43 收藏 0 点赞 0 评论 0
/**
 * 创建解析器
 *
 * @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;
}
Types.java 文件源码 项目:guava-mock 阅读 47 收藏 0 点赞 0 评论 0
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();
}
Key.java 文件源码 项目:booter-injector 阅读 58 收藏 0 点赞 0 评论 0
/**
 * 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);
}
ReflectionUtils.java 文件源码 项目:BIMplatform 阅读 47 收藏 0 点赞 0 评论 0
/** 
 * 通过反射, 获得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];  
}
ReflectUtils.java 文件源码 项目:spring-boot-elastcsearch-example 阅读 47 收藏 0 点赞 0 评论 0
/**
 * 得到指定类型的指定位置的泛型实参
 * @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];
}
InitMethodUtil.java 文件源码 项目:DUnit 阅读 54 收藏 0 点赞 0 评论 0
/**
 * 创建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;
}
ReflectionUtils.java 文件源码 项目:gitplex-mit 阅读 45 收藏 0 点赞 0 评论 0
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;
}
ClassUtil.java 文件源码 项目:util 阅读 46 收藏 0 点赞 0 评论 0
/**
 * 通过反射, 获得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];
}
Field.java 文件源码 项目:dtmlibs 阅读 50 收藏 0 点赞 0 评论 0
@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;
}
GsonType.java 文件源码 项目:stynico 阅读 51 收藏 0 点赞 0 评论 0
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;
}


问题


面经


文章

微信
公众号

扫码关注公众号