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

The following examples show how to use com.google.common.reflect.TypeToken#getRawType() . 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: ModelInfoLookup.java    From archie with Apache License 2.0 6 votes vote down vote up
private Class getTypeInCollection(TypeToken fieldType) {
    Class rawFieldType = fieldType.getRawType();
    if (Collection.class.isAssignableFrom(rawFieldType)) {
        Type[] actualTypeArguments = ((ParameterizedType) fieldType.getType()).getActualTypeArguments();
        if (actualTypeArguments.length == 1) {
            //the java reflection api is kind of tricky with types. This works for the archie RM, but may cause problems for other RMs. The fix is implementing more ways
            if (actualTypeArguments[0] instanceof Class) {
                return (Class) actualTypeArguments[0];
            } else if (actualTypeArguments[0] instanceof ParameterizedType) {
                ParameterizedType parameterizedTypeInCollection = (ParameterizedType) actualTypeArguments[0];
                return (Class) parameterizedTypeInCollection.getRawType();
            } else if (actualTypeArguments[0] instanceof java.lang.reflect.TypeVariable) {
                return (Class) ((java.lang.reflect.TypeVariable) actualTypeArguments[0]).getBounds()[0];
            }
        }
    }
    return rawFieldType;
}
 
Example 2
Source File: Methods.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
private static @Nullable String invocationFailureReason(Invokable<?, ?> to, Invokable<?, ?> from) {
    final String reason = invocationFailureReason(methodType(to), methodType(from));
    if(reason != null) return reason;

    thrownLoop: for(TypeToken<? extends Throwable> thrown : from.getExceptionTypes()) {
        final Class<?> thrownRaw = thrown.getRawType();
        if(Error.class.isAssignableFrom(thrownRaw)) continue;
        if(RuntimeException.class.isAssignableFrom(thrownRaw)) continue ;
        for(TypeToken<? extends Throwable> caught : to.getExceptionTypes()) {
            if(caught.getRawType().isAssignableFrom(thrownRaw)) continue thrownLoop;
        }
        return "unhandled exception " + thrown.getRawType().getName();
    }

    return null;
}
 
Example 3
Source File: SwaggerGenerator.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
private static Property getSwaggerArrayProperty(TypeToken<?> typeToken) {
  Class<?> type = typeToken.getRawType();
  if (type == String.class) {
    return new StringProperty();
  } else if (type == Boolean.class || type == Boolean.TYPE) {
    return new BooleanProperty();
  } else if (type == Integer.class || type == Integer.TYPE) {
    return new IntegerProperty();
  } else if (type == Long.class || type == Long.TYPE) {
    return new LongProperty();
  } else if (type == Float.class || type == Float.TYPE) {
    return new FloatProperty();
  } else if (type == Double.class || type == Double.TYPE) {
    return new DoubleProperty();
  } else if (type == byte[].class) {
    return new ByteArrayProperty();
  } else if (type.isEnum()) {
    return new StringProperty();
  }
  throw new IllegalArgumentException("invalid property type");
}
 
Example 4
Source File: ConverterMapInbound.java    From OpenPeripheral with MIT License 6 votes vote down vote up
@Override
public Object toJava(IConverter registry, Object obj, Type expected) {

	if (obj instanceof Map) {
		final TypeToken<?> type = TypeToken.of(expected);
		if (type.getRawType() == Map.class) {
			final Type keyType = type.resolveType(TypeUtils.MAP_KEY_PARAM).getType();
			final Type valueType = type.resolveType(TypeUtils.MAP_VALUE_PARAM).getType();

			Map<Object, Object> result = Maps.newHashMap();

			for (Map.Entry<?, ?> e : ((Map<?, ?>)obj).entrySet()) {
				Object key = TypeConverter.nullableToJava(registry, e.getKey(), keyType);
				Object value = TypeConverter.nullableToJava(registry, e.getValue(), valueType);
				result.put(key, value);
			}

			return result;
		}
	}

	return null;
}
 
Example 5
Source File: OptionalTypeFixtureConverter.java    From beanmother with Apache License 2.0 6 votes vote down vote up
/**
 * Convert for a target of Optional
 */
@Override
public Object convert(FixtureTemplate fixtureTemplate, TypeToken typeToken) {
    if (typeToken.getRawType() != Optional.class) {
        return fixtureConverter.convert(fixtureTemplate, typeToken);
    }
    List<TypeToken<?>> types = TypeTokenUtils.extractGenericTypeTokens(typeToken);
    if (types.isEmpty()) {
        if (fixtureTemplate instanceof FixtureValue) {
            Object value = ((FixtureValue) fixtureTemplate).getValue();
            return Optional.of(value);
        }
        return null;
    } else {
        return Optional.of(fixtureConverter.convert(fixtureTemplate, types.get(0)));
    }
}
 
Example 6
Source File: OptionalTypeFixtureConverter.java    From beanmother with Apache License 2.0 6 votes vote down vote up
/**
 * Convert for a target of Optional

 */
@Override
public Object convert(FixtureTemplate fixtureTemplate, TypeToken typeToken) {
    if (typeToken.getRawType() != Optional.class) {
        return fixtureConverter.convert(fixtureTemplate, typeToken);
    }
    List<TypeToken<?>> types = TypeTokenUtils.extractGenericTypeTokens(typeToken);
    if (types.isEmpty()) {
        if (fixtureTemplate instanceof FixtureValue) {
            Object value = ((FixtureValue) fixtureTemplate).getValue();
            return Optional.of(value);
        }
        return null;
    } else {
        return Optional.of(fixtureConverter.convert(fixtureTemplate, types.get(0)));
    }
}
 
Example 7
Source File: StringToEnumConverter.java    From beanmother with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object convert(Object source, TypeToken<?> targetTypeToken) {
    if (!canHandle(source, targetTypeToken)) throw new ConverterException(source, targetTypeToken.getRawType());

    Class enumClass = targetTypeToken.getRawType();
    for (Object enumConstant : enumClass.getEnumConstants()) {
        String enumStr = enumConstant.toString().replaceAll("\\_", "");
        String sourceStr = ((String) source).replaceAll("\\-", "").replaceAll("\\_", "").replaceAll("\\s", "");
        if (enumStr.equalsIgnoreCase(sourceStr)) {
            return Enum.valueOf(enumClass, enumConstant.toString());
        }
    }

    throw new ConverterException(source, targetTypeToken.getRawType(), "can not find enum constants");
}
 
Example 8
Source File: BasicParameterType.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public BasicParameterType(String name, TypeToken<T> type, String description, T defaultValue, boolean hasDefaultValue) {
    this.name = name;
    if (type!=null && type.equals(TypeToken.of(type.getRawType()))) {
        // prefer Class if it's already a raw type; keeps persistence simpler (and the same as before)
        this.type = (Class<T>) type.getRawType();
    } else {
        this.typeT = type;
    }
    this.description = description;
    this.defaultValue = defaultValue;
    if (defaultValue!=null && !defaultValue.getClass().equals(Object.class)) {
        // if default value is null (or is an Object, which is ambiguous on resolution to to rebind), 
        // don't bother to set this as it creates noise in the persistence files
        this.hasDefaultValue = hasDefaultValue;
    }
}
 
Example 9
Source File: StringToJodaTimeBaseLocalConverter.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());
    }

    Date date = stringToDateConverter.convert(String.valueOf(source));
    return dateToJodaTimeBaseLocalConverter.convert(date, targetTypeToken);
}
 
Example 10
Source File: TypeTokens.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** given either a token or a raw type, returns the raw type */
@SuppressWarnings("unchecked")
public static <T,U extends T> Class<T> getRawType(TypeToken<U> token, Class<T> raw) {
    if (raw!=null) return raw;
    if (token!=null) return (Class<T>) token.getRawType();
    throw new IllegalStateException("Both indicators of type are null");
}
 
Example 11
Source File: TypeTokens.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** returns raw type, if it's raw, else null;
 * used e.g. to set only one of the raw type or the type token,
 * for instance to make serialized output nicer */
@Nullable
public static <T> Class<? super T> getRawTypeIfRaw(@Nullable TypeToken<T> type) {
    if (type==null || !type.equals(TypeToken.of(type.getRawType()))) {
        return null;
    } else {
        return type.getRawType();
    }
}
 
Example 12
Source File: SmartCallFactory.java    From SmartCache with Apache License 2.0 5 votes vote down vote up
@Override
public CallAdapter<?, ?> get(final Type returnType, final Annotation[] annotations,
                                     final Retrofit retrofit) {

    TypeToken<?> token = TypeToken.of(returnType);
    if (token.getRawType() != SmartCall.class) {
        return null;
    }

    if (!(returnType instanceof ParameterizedType)) {
        throw new IllegalStateException(
                "SmartCall must have generic type (e.g., SmartCall<ResponseBody>)");
    }

    final Type responseType = ((ParameterizedType) returnType).getActualTypeArguments()[0];
    final Executor callbackExecutor = asyncExecutor;

    return new CallAdapter<Object, SmartCall<?>>() {
        @Override
        public Type responseType() {
            return responseType;
        }

        @Override
        public SmartCall<?> adapt(Call<Object> call) {
            return new SmartCallImpl<>(callbackExecutor, call, responseType(), annotations,
                    retrofit, cachingSystem);
        }
    };
}
 
Example 13
Source File: Reflections.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static TypeToken<?>[] getGenericParameterTypeTokens(TypeToken<?> t) {
    Class<?> rawType = t.getRawType();
    TypeVariable<?>[] pT = rawType.getTypeParameters();
    TypeToken<?> pTT[] = new TypeToken<?>[pT.length];
    for (int i=0; i<pT.length; i++) {
        pTT[i] = t.resolveType(pT[i]);
    }
    return pTT;
}
 
Example 14
Source File: CommonAdaptorTryCoercions.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> Maybe<T> tryCoerce(Object input, TypeToken<T> targetType) {
    Class<? super T> rawTargetType = targetType.getRawType();
    
    //for enums call valueOf with the string representation of the value
    if (rawTargetType.isEnum()) {
        return EnumTypeCoercions.tryCoerceUntyped(Strings.toString(input), (Class<T>)rawTargetType);
    } else {
        return null;
    }
}
 
Example 15
Source File: IndexedTypeInfoBuilder.java    From OpenPeripheral with MIT License 5 votes vote down vote up
private static ITypesProvider createTypesProvider(TypeToken<?> fieldType) {
	if (CUSTOM_PROPERTY_TYPE.isAssignableFrom(fieldType)) {
		if (CUSTOM_TYPED_PROPERTY_TYPE.isAssignableFrom(fieldType)) return new CustomTypedPropertyTypesProvider(fieldType);
		else return new CustomPropertyTypesProvider(fieldType);
	}

	if (TypeUtils.MAP_TOKEN.isAssignableFrom(fieldType)) return new MapTypesProvider(fieldType);
	if (TypeUtils.LIST_TOKEN.isAssignableFrom(fieldType)) return new ListTypesProvider(fieldType);
	if (fieldType.isArray()) return new ArrayTypesProvider(fieldType);
	final Class<?> rawType = fieldType.getRawType();

	if (StructHandlerProvider.instance.isStruct(rawType)) return new StructTypesProvider(rawType);

	throw new IllegalArgumentException("Failed to deduce value type from" + fieldType);
}
 
Example 16
Source File: ClassArgumentConverter.java    From junit5-extensions with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object convert(Object input, ParameterContext context) throws ArgumentConversionException {
  TypeToken<?> parameterType = TypeToken.of(context.getParameter().getParameterizedType());
  if (parameterType.getRawType() != Class.class) {
    throw new ArgumentConversionException(
        String.format("Could not convert: %s. Invalid parameter type.", input));
  }

  return convert(input.toString(), (TypeToken<? extends Class<?>>) parameterType);
}
 
Example 17
Source File: DiscoveryGenerator.java    From endpoints-java with Apache License 2.0 4 votes vote down vote up
private JsonSchema convertMethodParameter(
    ApiParameterConfig parameterConfig, boolean isPathParameter) {
  JsonSchema schema = new JsonSchema();
  TypeToken<?> type;
  if (parameterConfig.isRepeated()) {
    schema.setRepeated(true);
    type = parameterConfig.getRepeatedItemSerializedType();
  } else {
    type = parameterConfig.getSchemaBaseType();
  }

  if (parameterConfig.isEnum()) {
    List<String> enumValues = Lists.newArrayList();
    List<String> enumDescriptions = Lists.newArrayList();
    for (java.lang.reflect.Field field : type.getRawType().getFields()) {
      if (field.isEnumConstant()) {
        enumValues.add(field.getName());
        Description description = field.getAnnotation(Description.class);
        enumDescriptions.add(description == null ? "" : description.value());
      }
    }
    schema.setEnum(enumValues);
    schema.setEnumDescriptions(enumDescriptions);

    type = TypeToken.of(String.class);
  }

  schema.setType(typeLoader.getSchemaType(type));
  schema.setFormat(FieldType.fromType(type).getDiscoveryFormat());
  if (!parameterConfig.getNullable() && parameterConfig.getDefaultValue() == null) {
    schema.setRequired(true);
  }
  // TODO: Try to find a way to move default value interpretation/conversion into the
  // general configuration code.
  String defaultValue = parameterConfig.getDefaultValue();
  if (defaultValue != null) {
    Class<?> parameterClass = type.getRawType();
    try {
      objectMapper.convertValue(defaultValue, parameterClass);
    } catch (IllegalArgumentException e) {
      throw new IllegalArgumentException(String.format(
          "'%s' is not a valid default value for type '%s'", defaultValue, type));
    }
    schema.setDefault(defaultValue);
  }

  if (isPathParameter) {
    schema.setLocation("path");
  } else {
    schema.setLocation("query");
  }
  if (parameterConfig.getDescription() != null) {
    schema.setDescription(parameterConfig.getDescription());
  }
  return schema;
}
 
Example 18
Source File: SingleTypeInfoBuilder.java    From OpenPeripheral with MIT License 4 votes vote down vote up
public CustomPropertyProviderBase(TypeToken<?> fieldType, TypeVariable<?> var) {
	this.fieldType = fieldType.getRawType();
	this.valueType = fieldType.resolveType(var).getType();
}
 
Example 19
Source File: DefaultTypeClassifier.java    From OpenPeripheral with MIT License 4 votes vote down vote up
private static IScriptType createListType(ITypeClassifier classifier, TypeToken<?> type) {
	return (type.getRawType() != Object.class)
			? new ListType(classifier.classifyType(type.getType()))
			: SingleArgType.TABLE;
}
 
Example 20
Source File: ModelInfoLookup.java    From archie with Apache License 2.0 4 votes vote down vote up
private void addRMAttributeInfo(Class clazz, RMTypeInfo typeInfo, TypeToken typeToken, Field field) {
    String attributeName = namingStrategy.getAttributeName(field);
    String javaFieldName = field.getName();
    String javaFieldNameUpperCased = upperCaseFirstChar(javaFieldName);
    Method getMethod = getMethod(clazz, "get" + javaFieldNameUpperCased);
    Method setMethod = null, addMethod = null;
    if (getMethod == null) {
        getMethod = getMethod(clazz, "is" + javaFieldNameUpperCased);
    }
    if (getMethod != null) {
        setMethod = getMethod(clazz, "set" + javaFieldNameUpperCased, getMethod.getReturnType());
        addMethod = getAddMethod(clazz, typeToken, field, javaFieldNameUpperCased, getMethod);
    } else {
        logger.warn("No get method found for field {} on class {}", field.getName(), clazz.getSimpleName());
    }

    TypeToken fieldType = null;
    if (getMethod != null) {
        fieldType = typeToken.resolveType(getMethod.getGenericReturnType());
    } else {
        fieldType = typeToken.resolveType(field.getGenericType());
    }

    Class rawFieldType = fieldType.getRawType();
    Class typeInCollection = getTypeInCollection(fieldType);
    if (setMethod != null) {
        RMAttributeInfo attributeInfo = new RMAttributeInfo(
                attributeName,
                field,
                rawFieldType,
                typeInCollection,
                field.getAnnotation(Nullable.class) != null,
                getMethod,
                setMethod,
                addMethod
        );
        typeInfo.addAttribute(attributeInfo);
    } else {
        logger.info("property without a set method ignored for field {} on class {}", field.getName(), clazz.getSimpleName());
    }
}