Example usage for com.google.common.reflect TypeToken of

List of usage examples for com.google.common.reflect TypeToken of

Introduction

In this page you can find the example usage for com.google.common.reflect TypeToken of.

Prototype

public static TypeToken<?> of(Type type) 

Source Link

Document

Returns an instance of type token that wraps type .

Usage

From source file:org.zalando.riptide.Conditions.java

public static <A, I> TypedCondition<A, I> on(final A attribute, final Class<I> type) {
    return on(attribute, TypeToken.of(type));
}

From source file:co.cask.cdap.etl.common.TypeChecker.java

public static Class getParameterClass(Object instance, Class instanceClass, int parameterNumber) {
    return TypeToken.of(instance.getClass()).resolveType(instanceClass.getTypeParameters()[parameterNumber])
            .getRawType();//w ww.  j  a  v  a 2 s.c  om
}

From source file:brooklyn.util.guava.TypeTokens.java

/** 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//from w  w  w  .j  a  v  a2  s.c  o m
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();
    }
}

From source file:com.facebook.presto.matching.MatchingEngine.java

private static Stream<Class<?>> supertypes(Class<?> type) {
    return TypeToken.of(type).getTypes().stream().map(TypeToken::getRawType);
}

From source file:org.eclipse.gef4.common.reflect.Types.java

/**
 * Constructs a new {@link TypeToken} for an actual parameter type, which is
 * inferred from a given context class./*from  w  w w .  j  a  va  2 s .c o m*/
 *
 * @param <T>
 *            The parameter type to use.
 * @param contextClass
 *            A class that can be used to infer the actual parameter type of
 *            the parameterized type.
 * @return A new TypeToken representing the parameterized type.
 */
@SuppressWarnings("unchecked")
public static <T> TypeToken<T> argumentOf(Class<?> contextClass) {
    return (TypeToken<T>) TypeToken
            .of(((ParameterizedType) contextClass.getGenericSuperclass()).getActualTypeArguments()[0]);
}

From source file:ru.custis.beanpath.BeanPathMagic.java

@SuppressWarnings("unchecked")
public static @Nonnull <T> T root(@Nonnull Class<T> clazz) {
    Assert.notNull(clazz, "clazz");
    return (T) Mocker.mock(TypeToken.of(clazz));
}

From source file:net.derquinse.common.meta.MetaClass.java

/**
 * Returns the metaclass for a type, discovering it if needed.
 * @param type Type./*w  w w  .jav  a 2  s  .c o m*/
 * @return The meta class.
 */
public static <T extends WithMetaClass> MetaClass<T> of(Class<T> type) {
    return of(TypeToken.of(type));
}

From source file:io.v.rx.syncbase.RangeWatchEvent.java

public static <T> RangeWatchEvent<T> fromWatchChange(final WatchChange c, final Class<T> type)
        throws VException {
    return fromWatchChange(c, TypeToken.of(type));
}

From source file:com.salesforce.grpc.contrib.MoreMetadata.java

/**
 * A metadata marshaller that encodes objects as JSON using the google-gson library.
 *
 * <p>All non-ascii characters are unicode escaped to comply with {@code AsciiMarshaller}'s character range
 * requirements.// ww w.j  a v  a  2  s .co m
 *
 * @param clazz the type to serialize
 * @param <T>
 */
public static final <T> Metadata.AsciiMarshaller<T> JSON_MARSHALLER(Class<T> clazz) {
    return new Metadata.AsciiMarshaller<T>() {
        TypeToken<T> typeToken = TypeToken.of(clazz);
        private Gson gson = new Gson();

        @Override
        public String toAsciiString(T value) {
            try {
                try (StringWriter sw = new StringWriter()) {
                    gson.toJson(value, typeToken.getType(), new UnicodeEscapingAsciiWriter(sw));
                    return sw.toString();
                }
            } catch (IOException e) {
                throw new IllegalArgumentException(e);
            }
        }

        @Override
        public T parseAsciiString(String serialized) {
            return gson.fromJson(serialized, typeToken.getType());
        }
    };
}

From source file:com.microsoft.rest.Validator.java

/**
 * 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
 *///from   w ww . j a  v a2  s  . co  m
public static void validate(Object parameter) throws IllegalArgumentException {
    // 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()
            || parameterToken.isAssignableFrom(LocalDate.class)
            || parameterToken.isAssignableFrom(DateTime.class) || parameterToken.isAssignableFrom(String.class)
            || parameterToken.isAssignableFrom(DateTimeRfc1123.class)
            || parameterToken.isAssignableFrom(Period.class)) {
        return;
    }

    for (Class<?> c : parameterToken.getTypes().classes().rawTypes()) {
        // Ignore checks for Object type.
        if (c.isAssignableFrom(Object.class)) {
            continue;
        }
        for (Field field : c.getDeclaredFields()) {
            field.setAccessible(true);
            JsonProperty annotation = field.getAnnotation(JsonProperty.class);
            Object property;
            try {
                property = field.get(parameter);
            } catch (IllegalAccessException e) {
                throw new IllegalArgumentException(e.getMessage(), e);
            }
            if (property == null) {
                if (annotation != null && annotation.required()) {
                    throw new IllegalArgumentException(field.getName() + " is required and cannot be null.");
                }
            } else {
                try {
                    Class<?> propertyType = property.getClass();
                    if (TypeToken.of(List.class).isAssignableFrom(propertyType)) {
                        List<?> items = (List<?>) property;
                        for (Object item : items) {
                            Validator.validate(item);
                        }
                    } else if (TypeToken.of(Map.class).isAssignableFrom(propertyType)) {
                        Map<?, ?> entries = (Map<?, ?>) property;
                        for (Map.Entry<?, ?> entry : entries.entrySet()) {
                            Validator.validate(entry.getKey());
                            Validator.validate(entry.getValue());
                        }
                    } else if (parameterType != propertyType) {
                        Validator.validate(property);
                    }
                } catch (IllegalArgumentException ex) {
                    if (ex.getCause() == null) {
                        // Build property chain
                        throw new IllegalArgumentException(field.getName() + "." + ex.getMessage());
                    } else {
                        throw ex;
                    }
                }
            }
        }
    }
}