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

The following examples show how to use com.google.common.reflect.TypeToken#isArray() . 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: DefaultTypeClassifier.java    From OpenPeripheral with MIT License 6 votes vote down vote up
@Override
public IScriptType classify(ITypeClassifier classifier, Type type) {
	final TypeToken<?> typeToken = TypeToken.of(type);

	{
		Class<?> cls = TypeUtils.toObjectType(typeToken.getRawType());

		if (cls == String.class) return SingleArgType.STRING;
		if (cls == UUID.class) return SingleArgType.STRING;
		if (cls == Boolean.class) return SingleArgType.BOOLEAN;
		if (cls == Void.class) return SingleArgType.VOID;
		if (Number.class.isAssignableFrom(cls)) return SingleArgType.NUMBER;

		if (cls.isEnum()) return TypeHelper.bounded(SingleArgType.STRING, EnumeratedRange.create(cls.getEnumConstants()));
		if (StructHandlerProvider.instance.isStruct(cls)) return classifyStruct(classifier, cls);
	}

	if (typeToken.isArray()) return classifyArrayType(classifier, typeToken);
	else if (TypeUtils.MAP_TOKEN.isAssignableFrom(typeToken)) return classifyMapType(classifier, typeToken);
	else if (TypeUtils.SET_TOKEN.isAssignableFrom(typeToken)) return classifySetType(classifier, typeToken);
	else if (TypeUtils.COLLECTION_TOKEN.isAssignableFrom(typeToken)) return classifyCollectionType(classifier, typeToken);

	return null;
}
 
Example 2
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 3
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 4
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) {
    if (!targetType.isArray()) return null;
    
    TypeToken<?> targetComponentType = targetType.getComponentType();
    Iterable<?> castInput;
    if (input.getClass().isArray()) {
        castInput = Reflections.arrayToList(input);
    } else if (Iterable.class.isAssignableFrom(input.getClass())) {
        castInput = (Iterable<?>) input;
    } else {
        return null;
    }
    
    Object result = Array.newInstance(targetComponentType.getRawType(), Iterables.size(castInput));
    int index = 0;
    for (Object member : castInput) {
        Maybe<?> coercedMember = coercer.tryCoerce(member, targetComponentType);
        if (coercedMember == null || coercedMember.isAbsent()) {
            RuntimeException cause = Maybe.Absent.getException(coercedMember);
            return Maybe.absent("Array member at index "+index+" cannot be coerced to "+targetComponentType, cause);
        }
        Array.set(result, index++, coercedMember.get());
    }
    return (Maybe<T>) Maybe.of(result);
}
 
Example 5
Source File: ConverterArrayInbound.java    From OpenPeripheral with MIT License 5 votes vote down vote up
@Override
public Object toJava(IConverter registry, Object o, Type required) {
	if (o instanceof Map) {
		final TypeToken<?> type = TypeToken.of(required);
		if (type.isArray()) return converter.convertToContainer(registry, o, type);
	}

	return null;
}
 
Example 6
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 7
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 8
Source File: MethodParamsCodec.java    From OpenModsLib with MIT License 4 votes vote down vote up
private void validate(TypeToken<?> type) {
	Preconditions.checkState(!type.isPrimitive() || !isNullable, "Primitive types can't be nullable");
	if (type.isArray()) validate(type.getComponentType());
}