Java Code Examples for com.google.common.reflect.TypeToken#getType()

The following examples show how to use com.google.common.reflect.TypeToken#getType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReflectUtils.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> Class<T> getFieldArgument(Class<?> genericCls, String fieldName) {
  try {
    Type generic = FieldUtils.getField(genericCls, fieldName).getGenericType();
    TypeToken<?> token = TypeToken.of(genericCls).resolveType(generic);
    Type fieldType = token.getType();
    Type argument = ((ParameterizedType) fieldType).getActualTypeArguments()[0];
    if (argument instanceof GenericArrayType) {
      return (Class<T>) TypeToken.of(argument).getRawType();
    }

    return (Class<T>) argument;
  } catch (Throwable e) {
    throw new IllegalStateException("Failed to get generic argument.", e);
  }
}
 
Example 2
Source File: EndpointMethod.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
private void validateNoWildcards(TypeToken<?>[] types) {
  for (TypeToken<?> type : types) {
    Type resolved = type.getType();
    if (resolved instanceof ParameterizedType) {
      Class<?> clazz = type.getRawType();
      TypeToken<?>[] typeArgs = new TypeToken<?>[clazz.getTypeParameters().length];
      for (int i = 0; i < typeArgs.length; i++) {
        typeArgs[i] = type.resolveType(clazz.getTypeParameters()[i]);
      }
      validateNoWildcards(typeArgs);
    } else if (Types.isWildcardType(type)) {
      throw new IllegalArgumentException(
          // TODO: Figure out a more useful error message.  Maybe try to provide the
          // location of the wildcard instead of just its name ('T' is not the most useful info).
          String.format("Wildcard type %s not supported", resolved));
    }
  }
}
 
Example 3
Source File: PropertyListBuilder.java    From OpenPeripheral with MIT License 5 votes vote down vote up
public SingleParameters(String name, String getterDescription, String setterDescription, boolean isDelegating, boolean readOnly, boolean valueNullable, Class<?> valueType, ArgType valueDocType) {
	super(name, getterDescription, setterDescription, isDelegating, readOnly, valueNullable);

	final TypeToken<?> fieldType = TypeUtils.resolveFieldType(ownerClass, field);
	SingleTypeInfoBuilder typeInfoBuilder = new SingleTypeInfoBuilder(fieldType.getType());

	if (valueType != GetTypeFromField.class) typeInfoBuilder.overrideValueType(valueType);
	if (valueDocType != ArgType.AUTO) typeInfoBuilder.overrideValueDocType(TypeHelper.single(valueDocType));

	this.typeInfo = typeInfoBuilder.build();
}
 
Example 4
Source File: CollectionUtils.java    From OpenModsLib with MIT License 5 votes vote down vote up
private static Class<?> findTypeFromGenericInterface(Class<?> cls) {
	final TypeToken<?> token = TypeToken.of(cls);
	final TypeToken<?> typeB = token.resolveType(TypeUtils.FUNCTION_B_PARAM);
	if (typeB.getType() instanceof Class<?>) { return typeB.getRawType(); }

	return null;
}
 
Example 5
Source File: MessageRegistryTest.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testResolveGenericMessage() throws Exception {
    final TypeToken<? extends Message> token = registry.resolve("ModelUpdate", Optional.of("Server"));
    assertAssignableTo(new TypeToken<ModelUpdate<Server>>(){}, token);

    final Type type = token.getType();
    assertInstanceOf(ParameterizedType.class, type);
    final ParameterizedType pType = (ParameterizedType) type;
    assertEquals(ModelUpdate.class, pType.getRawType());
    assertEquals(Server.class, pType.getActualTypeArguments()[0]);
}
 
Example 6
Source File: JodaTimeSingleFieldPeriodConverter.java    From beanmother with Apache License 2.0 5 votes vote down vote up
@Override
public Object convert(Object source, TypeToken<?> targetTypeToken) {
    if (!canHandle(source, targetTypeToken)) {
        throw new ConverterException(source, targetTypeToken.getRawType());
    }

    Integer period = null;
    if (source instanceof Number) {
        period = (Integer) numberToNumberConverter.convert(source, TypeToken.of(Integer.class));
    } else if (source instanceof String) {
        period = (Integer) stringToNumberConverter.convert(source, TypeToken.of(Integer.class));
    }

    Type targetType = targetTypeToken.getType();

    if (targetType.equals(Seconds.class)) {
        return Seconds.seconds(period);
    } else if (targetType.equals(Minutes.class)) {
        return Minutes.minutes(period);
    } else if (targetType.equals(Hours.class)) {
        return Hours.hours(period);
    } else if (targetType.equals(Days.class)) {
        return Days.days(period);
    } else if (targetType.equals(Weeks.class)) {
        return Weeks.weeks(period);
    } else if (targetType.equals(Months.class)) {
        return Months.months(period);
    } else if (targetType.equals(Years.class)) {
        return Years.years(period);
    }

    throw new ConverterException(source, targetTypeToken.getRawType());
}
 
Example 7
Source File: ContainerConverterHelper.java    From OpenPeripheral with MIT License 5 votes vote down vote up
public R convertToContainer(IConverter registry, Object obj, TypeToken<?> type) {
	final TypeToken<?> componentType = getComponentType(type);

	final Map<?, ?> m = (Map<?, ?>)obj;

	if (m.isEmpty()) return createEmptyContainer(componentType);

	int indexMax = Integer.MIN_VALUE;

	final Map<Integer, Object> tmp = Maps.newHashMap();
	for (Map.Entry<?, ?> e : m.entrySet()) {
		final Object k = e.getKey();
		Preconditions.checkArgument(k instanceof Number, "Key '%s' is not number", k);
		int index = ((Number)k).intValue();
		Preconditions.checkArgument(index >= offset, "Indices must be larger than %s, got %s", offset, index);

		index -= offset;
		if (index > indexMax) indexMax = index;
		tmp.put(index, e.getValue());
	}

	final Type valueType = componentType.getType();

	final boolean isNullable = componentType.isPrimitive();

	final int size = indexMax + 1;
	R result = createNewContainer(componentType, size);

	for (int i = 0; i < size; i++) {
		Object o = tmp.get(i);
		if (o != null) {
			final Object converted = TypeConverter.nullableToJava(registry, isNullable, o, valueType);
			setResult(result, i, converted);
		}
	}

	return result;
}
 
Example 8
Source File: ApiAnnotationIntrospector.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
private static <T> TypeReference<T> typeReferenceOf(Transformer<?, T> serializer) {
  @SuppressWarnings("unchecked")
  Class<? extends Transformer<?, T>> serializerClass =
      (Class<? extends Transformer<?, T>>) serializer.getClass();
  final TypeToken<?> type = Serializers.getTargetType(serializerClass);
  return new TypeReference<T> (){
    @Override
    public Type getType() {
      return type.getType();
    }
  };
}
 
Example 9
Source File: PropertyListBuilder.java    From OpenPeripheral with MIT License 5 votes vote down vote up
public IndexedParameters(String name, String getterDescription, String setterDescription, boolean isDelegating, boolean readOnly, boolean valueNullable, boolean expandable, Class<?> keyType, ArgType keyDocType, Class<?> valueType, ArgType valueDocType) {
	super(name, getterDescription, setterDescription, isDelegating, readOnly, valueNullable);
	this.expandable = expandable;

	final TypeToken<?> fieldType = TypeUtils.resolveFieldType(ownerClass, field);
	final IndexedTypeInfoBuilder typeInfoBuilder = new IndexedTypeInfoBuilder(fieldType.getType());

	if (keyType != GetTypeFromField.class) typeInfoBuilder.overrideKeyType(keyType);
	if (keyDocType != ArgType.AUTO) typeInfoBuilder.overrideKeyDocType(TypeHelper.single(keyDocType));

	if (valueType != GetTypeFromField.class) typeInfoBuilder.overrideValueType(valueType);
	if (valueDocType != ArgType.AUTO) typeInfoBuilder.overrideValueDocType(TypeHelper.single(valueDocType));

	this.typeInfo = typeInfoBuilder.build();
}
 
Example 10
Source File: JacksonResourceSchemaProvider.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
private static boolean hasUnresolvedType(TypeToken<?> type) {
  Type javaType = type.getType();
  if (javaType instanceof ParameterizedType) {
    ParameterizedType p = (ParameterizedType) javaType;
    for (Type t : p.getActualTypeArguments()) {
      if (Types.isWildcardType(type.resolveType(t))) {
        logger.atWarning().log("skipping field of type '%s' because it is unresolved", type);
        return true;
      }
    }
  }
  return false;
}
 
Example 11
Source File: StructHandlerProvider.java    From OpenPeripheral with MIT License 5 votes vote down vote up
public FieldHandler(Class<?> ownerCls, Field field, String name, int index, boolean isOptional) {
	TypeToken<?> fieldType = TypeUtils.resolveFieldType(ownerCls, field);
	this.type = fieldType.getType();
	this.field = field;
	this.name = name;
	this.index = index;
	this.isOptional = isOptional;
}
 
Example 12
Source File: Types.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a simple name for a type that's suitable for use as a schema name. This will resolve any
 * transformations on the type, which may affect the type name.
 */
public static String getSimpleName(TypeToken<?> type, ApiSerializationConfig config) {
  if (type == null) {
    return null;
  }
  TypeToken<?> itemType = getArrayItemType(type);
  if (itemType != null) {
    return getSimpleName(itemType, config) + "Collection";
  } else if (type.getType() instanceof ParameterizedType) {
    Class<?> clazz = type.getRawType();
    StringBuilder builder = new StringBuilder();
    builder.append(clazz.getSimpleName());
    for (Type typeArg : clazz.getTypeParameters()) {
      builder.append('_');
      builder.append(getSimpleName(type.resolveType(typeArg), config));
    }
    return builder.toString();
  } else {
    Class<? extends Transformer<?, ?>> serializerClass = Iterables.getOnlyElement(
        Serializers.getSerializerClasses(type, config), null);
    if (serializerClass != null && ResourceTransformer.class.isAssignableFrom(serializerClass)) {
      @SuppressWarnings("unchecked")
      ResourceTransformer<?> resourceSerializer =
          (ResourceTransformer<?>) Serializers.instantiate(serializerClass, type);
      ResourceSchema resourceSchema = resourceSerializer.getResourceSchema();
      if (resourceSchema != null && resourceSchema.getName() != null) {
        return resourceSchema.getName();
      }
    }
    String collectionName = FieldType.fromType(type).getCollectionName();
    return collectionName != null ? collectionName : type.getRawType().getSimpleName();
  }
}
 
Example 13
Source File: Serializers.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Nullable
private static ParameterizedType getResolvedType(
    @Nullable Class<? extends Transformer<?, ?>> clazz) {
  if (clazz == null || !Transformer.class.isAssignableFrom(clazz)) {
      return null;
  }
  for (TypeToken<?> token : TypeToken.of(clazz).getTypes().interfaces()) {
    if (token.getRawType().equals(Transformer.class)) {
      Type tokenType = token.getType();
      return tokenType instanceof ParameterizedType ? (ParameterizedType) tokenType : null;
    }
  }
  return null;
}
 
Example 14
Source File: NullableCollectionSerializer.java    From OpenModsLib with MIT License 4 votes vote down vote up
public NullableCollectionSerializer(TypeToken<?> componentType) {
	final Type type = componentType.getType();
	this.componentSerializer = SerializerRegistry.instance.findSerializer(type);
	Preconditions.checkNotNull(componentSerializer, "Can't find serializer for %s", type);
	this.componentType = componentType;
}
 
Example 15
Source File: WebsocketMessageProcessor.java    From zheshiyigeniubidexiangmu with MIT License 4 votes vote down vote up
protected <T> BitmexResponse parseMessage(String message, TypeToken type) {
    Type collectionType = type.getType();
    BitmexResponse response = gson.fromJson(message, collectionType);
    return response;
}
 
Example 16
Source File: DefaultTypeCoercerFactory.java    From buck with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> TypeCoercer<?, ?> typeCoercerForTypeUnchecked(TypeToken<T> typeToken) {
  Type type = typeToken.getType();
  if (type instanceof TypeVariable) {
    type = ((TypeVariable<?>) type).getBounds()[0];
    if (Object.class.equals(type)) {
      throw new IllegalArgumentException("Generic types must be specific: " + type);
    }
  }

  if (type instanceof WildcardType) {
    type = ((WildcardType) type).getUpperBounds()[0];
    if (Object.class.equals(type)) {
      throw new IllegalArgumentException("Generic types must be specific: " + type);
    }
  }

  if (type instanceof Class) {
    Class<?> rawClass = Primitives.wrap((Class<?>) type);

    if (rawClass.isEnum()) {
      return enumCoercer(rawClass);
    }

    TypeCoercer<Object, ?> selectedTypeCoercer = null;
    for (TypeCoercer<Object, ?> typeCoercer : nonParameterizedTypeCoercers) {
      if (rawClass.isAssignableFrom(typeCoercer.getOutputType().getRawType())) {
        if (selectedTypeCoercer == null) {
          selectedTypeCoercer = typeCoercer;
        } else {
          throw new IllegalArgumentException("multiple coercers matched for type: " + type);
        }
      }
    }
    if (selectedTypeCoercer == null
        && DataTransferObject.class.isAssignableFrom(rawClass)
        && Types.getSupertypes(rawClass).stream()
            .anyMatch(c -> c.getAnnotation(RuleArg.class) != null)) {
      selectedTypeCoercer =
          new ImmutableTypeCoercer<>(
              getConstructorArgDescriptor((Class<? extends DataTransferObject>) rawClass));
    }
    if (selectedTypeCoercer != null) {
      return selectedTypeCoercer;
    } else {
      throw new IllegalArgumentException("no type coercer for type: " + type);
    }
  } else if (type instanceof ParameterizedType) {
    ParameterizedType parameterizedType = (ParameterizedType) type;
    return typeCoercerForParameterizedType(
        type.toString(),
        parameterizedType.getRawType(),
        parameterizedType.getActualTypeArguments());
  } else {
    throw new IllegalArgumentException("Cannot create type coercer for type: " + type);
  }
}
 
Example 17
Source File: Types.java    From endpoints-java with Apache License 2.0 4 votes vote down vote up
public static boolean isWildcardType(TypeToken<?> type) {
  Type javaType = type.getType();
  return javaType instanceof WildcardType
      || (javaType instanceof TypeVariable
          && ((TypeVariable) javaType).getName().startsWith("capture"));
}
 
Example 18
Source File: ServletRequestParamReader.java    From endpoints-java with Apache License 2.0 4 votes vote down vote up
protected Object[] deserializeParams(JsonNode node) throws IOException, IllegalAccessException,
    InvocationTargetException, NoSuchMethodException, ServiceException {
  EndpointMethod method = getMethod();
  Class<?>[] paramClasses = method.getParameterClasses();
  TypeToken<?>[] paramTypes = method.getParameterTypes();
  Object[] params = new Object[paramClasses.length];
  List<String> parameterNames = getParameterNames(method);
  for (int i = 0; i < paramClasses.length; i++) {
    TypeToken<?> type = paramTypes[i];
    Class<?> clazz = paramClasses[i];
    if (User.class.isAssignableFrom(clazz)) {
      // User type parameter requires no Named annotation (ignored if present)
      User user = getUser();
      if (user == null && methodConfig != null
          && methodConfig.getAuthLevel() == AuthLevel.REQUIRED) {
        throw new UnauthorizedException("Valid user credentials are required.");
      }
      if (user == null || clazz.isAssignableFrom(user.getClass())) {
        params[i] = user;
        logger.atFine().log("deserialize: User injected into param[%d]", i);
      } else {
        logger.atWarning().log(
            "deserialize: User object of type %s is not assignable to %s. User will be null.",
            user.getClass().getName(), clazz.getName());
      }
    } else if (APPENGINE_USER_CLASS_NAME.equals(clazz.getName())) {
      // User type parameter requires no Named annotation (ignored if present)
      com.google.appengine.api.users.User appEngineUser = getAppEngineUser();
      if (appEngineUser == null && methodConfig != null
          && methodConfig.getAuthLevel() == AuthLevel.REQUIRED) {
        throw new UnauthorizedException("Valid user credentials are required.");
      }
      params[i] = appEngineUser;
      logger.atFine().log("deserialize: App Engine User injected into param[%d]", i);
    } else if (clazz == HttpServletRequest.class) {
      // HttpServletRequest type parameter requires no Named annotation (ignored if present)
      params[i] = endpointsContext.getRequest();
      logger.atFine().log("deserialize: HttpServletRequest injected into param[%d]", i);
    } else if (clazz == ServletContext.class) {
      // ServletContext type parameter requires no Named annotation (ignored if present)
      params[i] = servletContext;
      logger.atFine().log("deserialize: ServletContext %s injected into param[%d]",
          params[i], i);
    } else {
      String name = parameterNames.get(i);
      if (Strings.isNullOrEmpty(name)) {
        params[i] = (node == null) ? null : objectReader.forType(clazz).readValue(node);
        logger.atFine().log("deserialize: %s %s injected into unnamed param[%d]",
            clazz, params[i], i);
      } else if (StandardParameters.isStandardParamName(name)) {
        params[i] = getStandardParamValue(node, name);
      } else {
        JsonNode nodeValue = node.get(name);
        if (nodeValue == null) {
          params[i] = null;
        } else {
          // Check for collection type
          if (Collection.class.isAssignableFrom(clazz)
              && type.getType() instanceof ParameterizedType) {
            params[i] =
                deserializeCollection(clazz, (ParameterizedType) type.getType(), nodeValue);
          } else {
            params[i] = objectReader.forType(clazz).readValue(nodeValue);
          }
        }
        if (params[i] == null && isRequiredParameter(method, i)) {
          throw new BadRequestException("null value for parameter '" + name + "' not allowed");
        }
        logger.atFine().log("deserialize: %s %s injected into param[%d] named {%s}",
            clazz, params[i], i, name);
      }
    }
  }
  return params;
}
 
Example 19
Source File: GsonStorageHandler.java    From helper with MIT License 4 votes vote down vote up
public GsonStorageHandler(String fileName, String fileExtension, File dataFolder, TypeToken<T> type, Gson gson) {
    this(fileName, fileExtension, dataFolder, type.getType(), gson);
}
 
Example 20
Source File: WebsocketMessageProcessor.java    From zheshiyigeniubidexiangmu with MIT License 4 votes vote down vote up
protected <T> BitmexResponse parseMessage(String message, TypeToken type) {
    Type collectionType = type.getType();
    BitmexResponse response = gson.fromJson(message, collectionType);
    return response;
}