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

The following examples show how to use com.google.common.reflect.TypeToken#isSubtypeOf() . 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: Digester.java    From divolte-collector with Apache License 2.0 6 votes vote down vote up
public Digester add(final ValueProducer<?> piece) {
    final TypeToken<?> producerType = piece.producerType;
    if (producerType.isSubtypeOf(String.class)) {
        @SuppressWarnings("unchecked")
        final ValueProducer<String> stringPiece = (ValueProducer<String>) piece;
        return addStringValueProducer(stringPiece);
    } else if (producerType.isSubtypeOf(JsonNode.class)) {
        @SuppressWarnings("unchecked")
        final ValueProducer<JsonNode> jsonPiece = (ValueProducer<JsonNode>) piece;
        return addJsonValueProducer(jsonPiece);
    } else if (producerType.isSubtypeOf(ByteBuffer.class)) {
        @SuppressWarnings("unchecked")
        final ValueProducer<ByteBuffer> bytesPiece = (ValueProducer<ByteBuffer>) piece;
        return addPiece(bytesPiece);
    }
    throw new SchemaMappingException("Cannot digest value of type: %s", producerType);
}
 
Example 2
Source File: StringToNumberConverter.java    From beanmother with Apache License 2.0 6 votes vote down vote up
@Override
public boolean canHandle(Object source, TypeToken<?> targetTypeToken) {
    if (targetTypeToken.isPrimitive()) {
        targetTypeToken = PrimitiveTypeUtils.toWrapperTypeToken(targetTypeToken);
    }
    if (!targetTypeToken.isSubtypeOf(Number.class)) return false;

    if (!(source instanceof String)) return false;

    try {
        NumberUtils.parseNumber((String) source, (Class) targetTypeToken.getType());
        return true;
    } catch (IllegalArgumentException e){
        return false;
    }
}
 
Example 3
Source File: SetSerializerProvider.java    From OpenModsLib with MIT License 5 votes vote down vote up
@Override
public IStreamSerializer<?> getSerializer(Type type) {
	TypeToken<?> typeToken = TypeToken.of(type);

	if (typeToken.isSubtypeOf(TypeUtils.SET_TOKEN)) {
		final TypeToken<?> componentType = typeToken.resolveType(TypeUtils.SET_VALUE_PARAM);
		return createSetSerializer(componentType);
	}

	return null;
}
 
Example 4
Source File: TypeTokenUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenCheckingIsSubtypeOf_shouldReturnTrueIfClassIsExtendedFrom() throws Exception {
    TypeToken<ArrayList<String>> stringList = new TypeToken<ArrayList<String>>() {
    };
    TypeToken<List> list = new TypeToken<List>() {
    };

    boolean isSubtypeOf = stringList.isSubtypeOf(list);

    assertTrue(isSubtypeOf);
}
 
Example 5
Source File: NumberToNumberConverter.java    From beanmother with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canHandle(Object source, TypeToken<?> targetTypeToken) {
    if (targetTypeToken.isPrimitive()) {
        targetTypeToken = PrimitiveTypeUtils.toWrapperTypeToken(targetTypeToken);
    }
    return TypeToken.of(source.getClass()).isSubtypeOf(Number.class)
            && targetTypeToken.isSubtypeOf(Number.class);
}
 
Example 6
Source File: TypeTokenUtils.java    From beanmother with Apache License 2.0 5 votes vote down vote up
/**
 * Extract TypeToken of generic type or Array component type.
 * @param typeToken Target TypeToken
 * @return generic TypeToken if typeToken is array or component TypeToken if typeToken is Array
 */
public static TypeToken<?> extractElementTypeToken(TypeToken<?> typeToken) {
    if (typeToken.isSubtypeOf(Collection.class)) {
        List<TypeToken<?>> genericTypeTokens = TypeTokenUtils.extractGenericTypeTokens(typeToken);
        if (genericTypeTokens.size() == 0) {
            return TypeToken.of(Object.class);
        } else {
            return genericTypeTokens.get(0);
        }
    } else if (typeToken.isArray()) {
        return typeToken.getComponentType();
    } else {
        throw new IllegalArgumentException("typeToken must be from List or array");
    }
}
 
Example 7
Source File: Types.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the element type of a type we want to treat as an array. Actual arrays or subtypes of
 * {@link java.util.Collection} can be treated as arrays. Returns null if the type cannot be
 * treated as an array.
 */
public static TypeToken<?> getArrayItemType(TypeToken<?> type) {
  if (type.isSubtypeOf(Collection.class)) {
    return type.resolveType(Collection.class.getTypeParameters()[0]);
  } else if (type.isArray()) {
    return type.getComponentType();
  }
  return null;
}
 
Example 8
Source File: Types.java    From endpoints-java with Apache License 2.0 4 votes vote down vote up
/**
 * Returns whether or not this type is an {@link Enum}.
 */
public static boolean isEnumType(TypeToken<?> type) {
  return type.isSubtypeOf(Enum.class);
}
 
Example 9
Source File: ApiMethodConfig.java    From endpoints-java with Apache License 2.0 4 votes vote down vote up
private boolean isValidCollectionType(TypeToken<?> type) {
  return type.isSubtypeOf(Collection.class) || Types.isCollectionResponseType(type);
}
 
Example 10
Source File: Types.java    From endpoints-java with Apache License 2.0 4 votes vote down vote up
public static boolean isCollectionResponseType(TypeToken<?> type) {
  return type.isSubtypeOf(CollectionResponse.class);
}
 
Example 11
Source File: Types.java    From endpoints-java with Apache License 2.0 4 votes vote down vote up
/**
 * Returns whether or not this type is a Google Java client library entity.
 */
public static boolean isJavaClientEntity(TypeToken<?> type) {
  return type.isSubtypeOf(GenericData.class);
}
 
Example 12
Source File: JodaTimeSingleFieldPeriodConverter.java    From beanmother with Apache License 2.0 4 votes vote down vote up
@Override
public boolean canHandle(Object source, TypeToken<?> targetTypeToken) {
    return targetTypeToken.isSubtypeOf(BaseSingleFieldPeriod.class)
            && ((source instanceof Number) || (stringToNumberConverter.canHandle(source, TypeToken.of(Long.class))));
}
 
Example 13
Source File: FixtureConverterImpl.java    From beanmother with Apache License 2.0 4 votes vote down vote up
/**
 * Convert the fixtureList to the given TypeToken
 * @param fixtureList
 * @param typeToken
 * @return converted object from fixtureList.
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
protected Object convert(FixtureList fixtureList, TypeToken<?> typeToken) {
    boolean isArray = typeToken.isArray();
    boolean isList = typeToken.isSubtypeOf(TypeToken.of(List.class));
    boolean isSet = typeToken.isSubtypeOf(TypeToken.of(Set.class));

    if (!isList && !isArray && !isSet) {
        throw new FixtureMappingException("Target setter of '" + fixtureList.getFixtureName() + "' must be List, Set or array.");
    }

    final List convertedList;
    if (isArray || typeToken.getRawType().isInterface()) {
        convertedList = new ArrayList();
    } else {
        try {
            convertedList = (List) typeToken.getRawType().newInstance();
        } catch (Exception e) {
            throw new FixtureMappingException(e);
        }
    }
    TypeToken<?> elementTypeToken = TypeTokenUtils.extractElementTypeToken(typeToken);


    for (FixtureTemplate template : fixtureList) {
        Object converted = convert(template, elementTypeToken);
        if (converted != null) {
            convertedList.add(converted);
        } else {
            logger.warn("Can not find converter for " + fixtureList.getFixtureName());
        }
    }

    // not found converter
    if (convertedList.size() == 0) return null;

    if(isArray) {
        if (elementTypeToken.isPrimitive()) {
            return PrimitiveTypeUtils.toWrapperListToPrimitiveArray(convertedList, (Class<?>) elementTypeToken.getType());
        } else {
            return Arrays.copyOf(convertedList.toArray(), convertedList.size(), (Class) typeToken.getRawType());
        }
    } else if (isSet) {
        Set set = new HashSet<>();
        set.addAll(convertedList);
        return set;
    } else {

        return convertedList;
    }
}
 
Example 14
Source File: ObjectToStringConverter.java    From beanmother with Apache License 2.0 4 votes vote down vote up
@Override
public boolean canHandle(Object source, TypeToken<?> targetTypeToken) {
    return (source != null) && targetTypeToken.isSubtypeOf(String.class);
}
 
Example 15
Source File: DateToJodaTimeBaseLocalConverter.java    From beanmother with Apache License 2.0 4 votes vote down vote up
@Override
public boolean canHandle(Object source, TypeToken<?> targetTypeToken) {
    return targetTypeToken.isSubtypeOf(BaseLocal.class) && (source instanceof Date);
}
 
Example 16
Source File: StringToJodaTimeBaseLocalConverter.java    From beanmother with Apache License 2.0 4 votes vote down vote up
@Override
public boolean canHandle(Object source, TypeToken<?> targetTypeToken) {
    return targetTypeToken.isSubtypeOf(BaseLocal.class) && stringToDateConverter.canHandle(source, TypeToken.of(Date.class));
}
 
Example 17
Source File: Types.java    From endpoints-java with Apache License 2.0 2 votes vote down vote up
/**
 * Returns whether or not this type is a {@link Map}. This excludes {@link GenericData}, which is
 * used by the Google Java client library as a supertype of resource types with concrete fields.
 */
public static boolean isMapType(TypeToken<?> type) {
  return type.isSubtypeOf(Map.class) && !isJavaClientEntity(type);
}
 
Example 18
Source File: Types.java    From endpoints-java with Apache License 2.0 2 votes vote down vote up
/**
 * Returns whether or not this type should be treated as a JSON array type. This includes all
 * array and {@link Collection} types, except for byte arrays, which are treated as base64
 * encoded strings.
 */
public static boolean isArrayType(TypeToken<?> type) {
  return getArrayItemType(type) != null && !type.isSubtypeOf(byte[].class);
}