Example usage for com.google.common.primitives Primitives allWrapperTypes

List of usage examples for com.google.common.primitives Primitives allWrapperTypes

Introduction

In this page you can find the example usage for com.google.common.primitives Primitives allWrapperTypes.

Prototype

public static Set<Class<?>> allWrapperTypes() 

Source Link

Document

Returns an immutable set of all nine primitive-wrapper types (including Void ).

Usage

From source file:at.yawk.cricket.template.Serializer.java

@SuppressWarnings({ "unchecked", "Convert2MethodRef" })
public Serializer() {
    special(String.class, CustomSerializer.IDENTITY);
    Primitives.allWrapperTypes().forEach(pr -> {
        if (Number.class.isAssignableFrom(pr)) {
            special(pr, (CustomSerializer) NUMBER);
        } else {//  w  w  w.j a va  2 s .  c om
            special(pr, CustomSerializer.IDENTITY);
        }
    });

    special(URL.class, CustomSerializer.TO_STRING);
    special(UUID.class, CustomSerializer.TO_STRING);

    special(Collection.class, (col, ser) -> {
        Stream serialized = col.stream().map((Object o) -> ser.serialize(o));
        return serialized.collect((Collector) Collectors.toList());
    });
    special(Map.class, (map, ser) -> {
        Map<Object, Object> serialized = new HashMap<>();
        map.forEach((k, v) -> serialized.put(ser.serialize(k), ser.serialize(v)));
        return serialized;
    });
    special(Optional.class, (opt, ser) -> opt.map(ser::serialize).orElse(null));
}

From source file:org.opendaylight.controller.cluster.datastore.DatastoreContextIntrospector.java

/**
 * Introspects each primitive wrapper (ie Integer, Long etc) and String type to find the
 * constructor that takes a single String argument. For primitive wrappers, this constructor
 * converts from a String representation.
 *//*  w  w  w.ja v  a2  s  . c o  m*/
private static void introspectPrimitiveTypes() {

    Set<Class<?>> primitives = ImmutableSet.<Class<?>>builder().addAll(Primitives.allWrapperTypes())
            .add(String.class).build();
    for (Class<?> primitive : primitives) {
        try {
            processPropertyType(primitive);
        } catch (Exception e) {
            // Ignore primitives that can't be constructed from a String, eg Character and Void.
        }
    }
}

From source file:com.google.errorprone.bugpatterns.threadsafety.WellKnownMutability.java

private static ImmutableMap<String, ImmutableAnnotationInfo> getBootstrapClasses() {
    return new Builder().addAll(Primitives.allPrimitiveTypes()).addAll(Primitives.allWrapperTypes())
            .add(java.lang.annotation.Annotation.class).add(java.lang.Class.class).add(java.lang.String.class)
            .add(java.math.BigDecimal.class).add(java.net.InetAddress.class).add(java.util.Locale.class)
            .add(java.util.regex.Pattern.class).add("java.util.Optional", "T").add("org.joda.time.DateTime")
            .add("org.joda.time.DateTimeZone").add("org.joda.time.Duration").add("org.joda.time.Instant")
            .add("org.joda.time.LocalDate").add("org.joda.time.LocalDateTime").add("org.joda.time.Period")
            .add("org.joda.time.format.DateTimeFormatter").add(com.google.common.primitives.UnsignedLong.class)
            .add(com.google.common.base.Converter.class).add("com.google.protobuf.ByteString")
            .add("com.google.protobuf.Descriptors$Descriptor")
            .add("com.google.protobuf.Descriptors$EnumDescriptor")
            .add("com.google.protobuf.Descriptors$EnumValueDescriptor")
            .add("com.google.protobuf.Descriptors$FieldDescriptor")
            .add("com.google.protobuf.Descriptors$FileDescriptor")
            .add("com.google.protobuf.Descriptors$ServiceDescriptor")
            .add("com.google.protobuf.ExtensionRegistry$ExtensionInfo").add("com.google.common.net.MediaType")
            .add("com.google.common.net.Uri").add("com.google.protobuf.Extension")
            .add("com.google.re2j.Pattern").add(com.google.common.collect.ImmutableCollection.class, "E")
            .add(com.google.common.collect.ImmutableSet.class, "E")
            .add(com.google.common.collect.ImmutableList.class, "E")
            .add(com.google.common.collect.ImmutableMultiset.class, "E")
            .add(com.google.common.collect.ImmutableMap.class, "K", "V")
            .add(com.google.common.collect.ImmutableBiMap.class, "K", "V")
            .add(com.google.common.collect.ImmutableMultimap.class, "K", "V")
            .add(com.google.common.collect.ImmutableListMultimap.class, "K", "V")
            .add(com.google.common.collect.ImmutableSetMultimap.class, "K", "V")
            .add(com.google.common.collect.ImmutableSortedMap.class, "K", "V")
            .add(com.google.common.collect.ImmutableRangeMap.class, "K", "V")
            .add(com.google.common.collect.ImmutableTable.class, "R", "C", "V")
            .add(com.google.common.base.Optional.class, "T").add(com.google.common.base.Splitter.class)
            .add(com.google.common.base.Joiner.class).add(com.google.common.collect.Range.class, "C")
            .add("android.net.Uri").add("java.time.Duration").add("java.time.Instant")
            .add("java.time.LocalDate").add("java.time.LocalDateTime").add("java.time.LocalTime")
            .add("java.time.MonthDay").add("java.time.OffsetDateTime").add("java.time.OffsetTime")
            .add("java.time.Period").add("java.time.Year").add("java.time.YearMonth")
            .add("java.time.ZonedDateTime").add("java.time.ZoneId").add("java.time.ZoneOffset")
            .add("java.time.chrono.AbstractChronology").add("java.time.chrono.ChronoLocalDate")
            .add("java.time.chrono.ChronoLocalDateTime", "D").add("java.time.chrono.Chronology")
            .add("java.time.chrono.ChronoPeriod").add("java.time.chrono.ChronoZonedDateTime", "D")
            .add("java.time.chrono.Era").add("java.time.chrono.HijrahChronology")
            .add("java.time.chrono.HijrahDate").add("java.time.chrono.IsoChronology")
            .add("java.time.chrono.JapaneseChronology").add("java.time.chrono.JapaneseDate")
            .add("java.time.chrono.JapaneseEra").add("java.time.chrono.MinguoChronology")
            .add("java.time.chrono.MinguoDate").add("java.time.chrono.ThaiBuddhistChronology")
            .add("java.time.chrono.ThaiBuddhistDate").add("java.time.format.DateTimeFormatter")
            .add("java.time.format.DecimalStyle").add("java.time.temporal.TemporalField")
            .add("java.time.temporal.TemporalUnit").add("java.time.temporal.ValueRange")
            .add("java.time.temporal.WeekFields").add("java.time.zone.ZoneOffsetTransition")
            .add("java.time.zone.ZoneOffsetTransitionRule").add("java.time.zone.ZoneRules")
            .add("java.time.zone.ZoneRulesProvider").build();
}

From source file:org.apache.brooklyn.util.javalang.coerce.PrimitiveStringTypeCoercions.java

public static boolean isPrimitiveOrBoxer(Class<?> type) {
    // cf Boxing.isPrimitiveOrBoxerClass
    return Primitives.allPrimitiveTypes().contains(type) || Primitives.allWrapperTypes().contains(type);
}

From source file:org.apache.brooklyn.util.javalang.coerce.PrimitiveStringTypeCoercions.java

@SuppressWarnings("unchecked")
public static <T> T stringToPrimitive(String value, Class<T> targetType) {
    assert Primitives.allPrimitiveTypes().contains(targetType)
            || Primitives.allWrapperTypes().contains(targetType) : "targetType=" + targetType;
    // If char, then need to do explicit conversion
    if (targetType == Character.class || targetType == char.class) {
        if (value.length() == 1) {
            return (T) (Character) value.charAt(0);
        } else if (value.length() != 1) {
            throw new ClassCoercionException("Cannot coerce type String to " + targetType.getCanonicalName()
                    + " (" + value + "): adapting failed");
        }/*from  w  w w  .java2  s .  c om*/
    }
    value = value.trim();
    // For boolean we could use valueOf, but that returns false whereas we'd rather throw errors on bad values
    if (targetType == Boolean.class || targetType == boolean.class) {
        if ("true".equalsIgnoreCase(value))
            return (T) Boolean.TRUE;
        if ("false".equalsIgnoreCase(value))
            return (T) Boolean.FALSE;
        if ("yes".equalsIgnoreCase(value))
            return (T) Boolean.TRUE;
        if ("no".equalsIgnoreCase(value))
            return (T) Boolean.FALSE;
        if ("t".equalsIgnoreCase(value))
            return (T) Boolean.TRUE;
        if ("f".equalsIgnoreCase(value))
            return (T) Boolean.FALSE;
        if ("y".equalsIgnoreCase(value))
            return (T) Boolean.TRUE;
        if ("n".equalsIgnoreCase(value))
            return (T) Boolean.FALSE;

        throw new ClassCoercionException("Cannot coerce type String to " + targetType.getCanonicalName() + " ("
                + value + "): adapting failed");
    }

    // Otherwise can use valueOf reflectively
    Class<?> wrappedType;
    if (Primitives.allPrimitiveTypes().contains(targetType)) {
        wrappedType = Primitives.wrap(targetType);
    } else {
        wrappedType = targetType;
    }

    try {
        return (T) wrappedType.getMethod("valueOf", String.class).invoke(null, value);
    } catch (Exception e) {
        ClassCoercionException tothrow = new ClassCoercionException(
                "Cannot coerce " + JavaStringEscapes.wrapJavaString(value) + " to "
                        + targetType.getCanonicalName() + " (" + value + "): adapting failed");
        tothrow.initCause(e);
        throw tothrow;
    }
}

From source file:brooklyn.util.flags.TypeCoercions.java

public static boolean isPrimitiveOrBoxer(Class<?> type) {
    return Primitives.allPrimitiveTypes().contains(type) || Primitives.allWrapperTypes().contains(type);
}

From source file:brooklyn.util.flags.TypeCoercions.java

@SuppressWarnings("unchecked")
public static <T> T stringToPrimitive(String value, Class<T> targetType) {
    assert Primitives.allPrimitiveTypes().contains(targetType)
            || Primitives.allWrapperTypes().contains(targetType) : "targetType=" + targetType;
    // If char, then need to do explicit conversion
    if (targetType == Character.class || targetType == char.class) {
        if (value.length() == 1) {
            return (T) (Character) value.charAt(0);
        } else if (value.length() != 1) {
            throw new ClassCoercionException("Cannot coerce type String to " + targetType.getCanonicalName()
                    + " (" + value + "): adapting failed");
        }/*from   w ww .  ja va  2s. c o m*/
    }
    value = value.trim();
    // For boolean we could use valueOf, but that returns false whereas we'd rather throw errors on bad values
    if (targetType == Boolean.class || targetType == boolean.class) {
        if ("true".equalsIgnoreCase(value))
            return (T) Boolean.TRUE;
        if ("false".equalsIgnoreCase(value))
            return (T) Boolean.FALSE;
        if ("yes".equalsIgnoreCase(value))
            return (T) Boolean.TRUE;
        if ("no".equalsIgnoreCase(value))
            return (T) Boolean.FALSE;
        if ("t".equalsIgnoreCase(value))
            return (T) Boolean.TRUE;
        if ("f".equalsIgnoreCase(value))
            return (T) Boolean.FALSE;
        if ("y".equalsIgnoreCase(value))
            return (T) Boolean.TRUE;
        if ("n".equalsIgnoreCase(value))
            return (T) Boolean.FALSE;

        throw new ClassCoercionException("Cannot coerce type String to " + targetType.getCanonicalName() + " ("
                + value + "): adapting failed");
    }

    // Otherwise can use valueOf reflectively
    Class<?> wrappedType;
    if (Primitives.allPrimitiveTypes().contains(targetType)) {
        wrappedType = Primitives.wrap(targetType);
    } else {
        wrappedType = targetType;
    }

    try {
        return (T) wrappedType.getMethod("valueOf", String.class).invoke(null, value);
    } catch (Exception e) {
        ClassCoercionException tothrow = new ClassCoercionException("Cannot coerce type String to "
                + targetType.getCanonicalName() + " (" + value + "): adapting failed");
        tothrow.initCause(e);
        throw tothrow;
    }
}

From source file:com.google.auto.value.processor.AutoAnnotationProcessor.java

/**
 * Returns the wrapper types ({@code Integer.class} etc) that are used in collection parameters
 * like {@code List<Integer>}. This is needed because we will emit a helper method for each such
 * type, for example to convert {@code Collection<Integer>} into {@code int[]}.
 *///from  w  w  w  .  ja v  a  2s .  co m
private Set<Class<?>> wrapperTypesUsedInCollections(ExecutableElement method) {
    TypeElement javaUtilCollection = processingEnv.getElementUtils().getTypeElement(Collection.class.getName());
    ImmutableSet.Builder<Class<?>> usedInCollections = ImmutableSet.builder();
    for (Class<?> wrapper : Primitives.allWrapperTypes()) {
        DeclaredType collectionOfWrapper = typeUtils.getDeclaredType(javaUtilCollection,
                getTypeMirror(wrapper));
        for (VariableElement parameter : method.getParameters()) {
            if (typeUtils.isAssignable(parameter.asType(), collectionOfWrapper)) {
                usedInCollections.add(wrapper);
                break;
            }
        }
    }
    return usedInCollections.build();
}

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

private static boolean isByRef(Class<?> param, Annotation[] annotations) {
    // if parameter has ByValue annotation, it is ByValueParameter
    if (containsAnnotation(annotations, ByValueParameter.class))
        return false;

    // if this is primitive or wrapper type, it is ByValueParameter
    if (param.isPrimitive() || param.equals(String.class) || Primitives.allWrapperTypes().contains(param))
        return false;

    // if this is enum, it is ByValueParameter
    if (param.isEnum())
        return false;

    // if parameter class has ByValueParameter annotation, it is ByValueParameter
    if (param.isAnnotationPresent(ByValueParameter.class))
        return false;

    // otherwise it is ByRefParameter
    return true;//from ww  w.jav a  2 s .com
}