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

The following examples show how to use com.google.common.reflect.TypeToken#isPrimitive() . 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: Types.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Test if an invocation conversion can be applied to the given types.
 *
 * https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.3
 */
public static boolean isConvertibleForInvocation(TypeToken<?> to, TypeToken<?> from) {
    if(to.isPrimitive()) {
        // Assigning to a primitive allows for both unboxing and primitive widening
        Class<?> fromRaw = from.getRawType();
        if(!fromRaw.isPrimitive()) {
            fromRaw = BOXINGS.inverse().get(fromRaw);
            if(fromRaw == null) return false;
        }
        return isPromotable(to.getRawType(), fromRaw);
    } else if(from.isPrimitive()) {
        // Assigning to an object from a primitive allows boxing and reference widening
        return to.isAssignableFrom(box(from.getRawType()));
    } else {
        return to.isAssignableFrom(from);
    }
}
 
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: Validator.java    From botbuilder-java with MIT License 5 votes vote down vote up
/**
 * Validates a user provided required parameter to be not null.
 * An {@link IllegalArgumentException} is thrown if a property fails the validation.
 *
 * @param parameter the parameter to validate
 * @throws IllegalArgumentException thrown when the Validator determines the argument is invalid
 */
public static void validate(Object parameter) {
    // Validation of top level payload is done outside
    if (parameter == null) {
        return;
    }

    Class parameterType = parameter.getClass();
    TypeToken<?> parameterToken = TypeToken.of(parameterType);
    if (Primitives.isWrapperType(parameterType)) {
        parameterToken = parameterToken.unwrap();
    }
    if (parameterToken.isPrimitive()
            || parameterType.isEnum()
            || parameterType == Class.class
            || parameterToken.isSupertypeOf(OffsetDateTime.class)
            || parameterToken.isSupertypeOf(ZonedDateTime.class)
            || parameterToken.isSupertypeOf(String.class)
            || parameterToken.isSupertypeOf(Period.class)) {
        return;
    }

    Annotation skipParentAnnotation = parameterType.getAnnotation(SkipParentValidation.class);

    if (skipParentAnnotation == null) {
        for (Class<?> c : parameterToken.getTypes().classes().rawTypes()) {
            validateClass(c, parameter);
        }
    } else {
        validateClass(parameterType, parameter);
    }
}
 
Example 4
Source File: NumberToNumberConverter.java    From beanmother with Apache License 2.0 5 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());
    if (targetTypeToken.isPrimitive()) {
        targetTypeToken = PrimitiveTypeUtils.toWrapperTypeToken(targetTypeToken);
    }
    return NumberUtils.convertNumberToTargetClass((Number) source, (Class) targetTypeToken.getType());
}
 
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: StringToNumberConverter.java    From beanmother with Apache License 2.0 5 votes vote down vote up
@Override
public Object convert(Object source, TypeToken<?> targetTypeToken) {
    if (targetTypeToken.isPrimitive()) {
        targetTypeToken = PrimitiveTypeUtils.toWrapperTypeToken(targetTypeToken);
    }

    if (canHandle(source, targetTypeToken)) {
        return NumberUtils.parseNumber((String) source, (Class) targetTypeToken.getType());
    } else {
        throw new ConverterException("can not convert '" + source + "' to " + targetTypeToken.getRawType());
    }
}
 
Example 7
Source File: Validator.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
/**
 * Validates a user provided required parameter to be not null.
 * An {@link IllegalArgumentException} is thrown if a property fails the validation.
 *
 * @param parameter the parameter to validate
 * @throws IllegalArgumentException thrown when the Validator determines the argument is invalid
 */
public static void validate(Object parameter) {
    // Validation of top level payload is done outside
    if (parameter == null) {
        return;
    }

    Class parameterType = parameter.getClass();
    TypeToken<?> parameterToken = TypeToken.of(parameterType);
    if (Primitives.isWrapperType(parameterType)) {
        parameterToken = parameterToken.unwrap();
    }
    if (parameterToken.isPrimitive()
            || parameterType.isEnum()
            || parameterType == Class.class
            || parameterToken.isSupertypeOf(LocalDate.class)
            || parameterToken.isSupertypeOf(DateTime.class)
            || parameterToken.isSupertypeOf(String.class)
            || parameterToken.isSupertypeOf(DateTimeRfc1123.class)
            || parameterToken.isSupertypeOf(Period.class)) {
        return;
    }

    Annotation skipParentAnnotation = parameterType.getAnnotation(SkipParentValidation.class);

    if (skipParentAnnotation == null) {
        for (Class<?> c : parameterToken.getTypes().classes().rawTypes()) {
            validateClass(c, parameter);
        }
    } else {
        validateClass(parameterType, parameter);
    }
}
 
Example 8
Source File: ArraySerializerProvider.java    From OpenModsLib with MIT License 5 votes vote down vote up
@Override
public IStreamSerializer<?> getSerializer(Class<?> cls) {
	if (cls.isArray()) {
		final TypeToken<?> componentCls = TypeToken.of(cls).getComponentType();
		return componentCls.isPrimitive()
				? createPrimitiveSerializer(componentCls)
				: createNullableSerializer(componentCls);
	}

	return null;
}
 
Example 9
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 10
Source File: Types.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public static <T> TypeToken<T> box(TypeToken<T> type) {
    return type.isPrimitive() ? TypeToken.of(box((Class<T>) type.getRawType())) : type;
}
 
Example 11
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;
    }
}