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

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

Introduction

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

Prototype

public final TypeSet getTypes() 

Source Link

Document

Returns the set of interfaces and classes that this type is or is a subtype of.

Usage

From source file:co.cask.tigon.internal.lang.Fields.java

/**
 * Find a {@link java.lang.reflect.Field} in the class hierarchy of the given type that passes the predicate.
 * @param classType The leaf class to start with.
 * @param fieldName Name of the field./*w w  w .j  a v  a 2s .com*/
 * @param predicate Predicate for accepting a matched field.
 * @return A {@link java.lang.reflect.Field} if found.
 * @throws NoSuchFieldException If the field is not found.
 */
public static Field findField(TypeToken<?> classType, String fieldName, Predicate<Field> predicate)
        throws NoSuchFieldException {
    for (Class<?> clz : classType.getTypes().classes().rawTypes()) {
        try {
            Field field = clz.getDeclaredField(fieldName);
            if (predicate.apply(field)) {
                return field;
            }
        } catch (NoSuchFieldException e) {
            // OK to ignore, keep finding.
        }
    }
    throw new NoSuchFieldException("Field " + fieldName + " not exists in the class hierarchy of " + classType);
}

From source file:org.datalorax.populace.core.util.TypeResolver.java

/**
 * Get a stream of all available aliases for the provided type variable found in any super types or implemented
 * generic interfaces of the provided {@code type}
 *
 * @param typeVar the type variable to find aliases for
 * @param type    the type whose super classes and interfaces to search for matching type variables
 * @return the type argument of any matching type variables found.
 *///from   ww w .  ja v  a2  s . co m
private static Stream<TypeVariable<?>> findSuperAndInterfaceTypeArgumentAliases(final TypeVariable<?> typeVar,
        final TypeToken<?> type) {
    return type.getTypes().stream().filter(t -> t.getType() instanceof ParameterizedType) // Ignore non-parameterized types
            .flatMap(t -> getTypeArgumentAliases(typeVar, t)); // For each parameterised get type argument aliases
}

From source file:org.lanternpowered.server.util.copy.CopyableTypes.java

private static Optional<Function> load(TypeToken<?> typeToken) {
    Function function = copyFunctions.get(typeToken);
    if (function != null) {
        return Optional.of(function);
    }//w  w w  . j av a 2s  .  co  m
    for (TypeToken<?> typeToken1 : typeToken.getTypes()) {
        function = copyFunctions.get(typeToken1);
        if (function != null) {
            return Optional.of(function);
        }
    }
    return Optional.empty();
}

From source file:com.google.shipshape.util.rpc.Method.java

static TypeToken getMethodInterface(Type t) {
    TypeToken token = TypeToken.of(t);
    Set<TypeToken> interfaces = token.getTypes().interfaces();
    for (TypeToken i : interfaces) {
        if (i.getRawType().equals(Method.ServerImpl.class)) {
            return i;
        }/*from www.j a va  2s.co m*/
    }
    throw new IllegalArgumentException("Type " + t + " does not implement the Method.ServerImpl interface");
}

From source file:co.cask.tigon.internal.lang.Reflections.java

/**
 * Inspect all members in the given type. Fields and Methods that are given to Visitor are
 * always having accessible flag being set.
 *//*from  w  ww. j  a va  2 s  .com*/
public static void visit(Object instance, TypeToken<?> inspectType, Visitor firstVisitor,
        Visitor... moreVisitors) {

    try {
        List<Visitor> visitors = ImmutableList.<Visitor>builder().add(firstVisitor).add(moreVisitors).build();

        for (TypeToken<?> type : inspectType.getTypes().classes()) {
            if (Object.class.equals(type.getRawType())) {
                break;
            }

            for (Field field : type.getRawType().getDeclaredFields()) {
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }
                for (Visitor visitor : visitors) {
                    visitor.visit(instance, inspectType, type, field);
                }
            }

            for (Method method : type.getRawType().getDeclaredMethods()) {
                if (!method.isAccessible()) {
                    method.setAccessible(true);
                }
                for (Visitor visitor : visitors) {
                    visitor.visit(instance, inspectType, type, method);
                }
            }
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:co.cask.cdap.internal.lang.Reflections.java

/**
 * Inspect all members in the given type. Fields and Methods that are given to Visitor are
 * always having accessible flag being set.
 *//*ww  w.  j  a  v  a 2 s  .co  m*/
public static void visit(Object instance, TypeToken<?> inspectType, Visitor firstVisitor,
        Visitor... moreVisitors) {

    try {
        List<Visitor> visitors = ImmutableList.<Visitor>builder().add(firstVisitor).add(moreVisitors).build();

        for (TypeToken<?> type : inspectType.getTypes().classes()) {
            if (Object.class.equals(type.getRawType())) {
                break;
            }

            for (Field field : type.getRawType().getDeclaredFields()) {
                if (field.isSynthetic()) {
                    continue;
                }
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }
                for (Visitor visitor : visitors) {
                    visitor.visit(instance, inspectType, type, field);
                }
            }

            for (Method method : type.getRawType().getDeclaredMethods()) {
                if (method.isSynthetic() || method.isBridge()) {
                    continue;
                }
                if (!method.isAccessible()) {
                    method.setAccessible(true);
                }
                for (Visitor visitor : visitors) {
                    visitor.visit(instance, inspectType, type, method);
                }
            }
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.datastore_android_sdk.reflect.Types.java

/**
 * Returns the parameterized type that is or extends the given type that
 * matches the given super class./* w  ww . jav  a  2 s. c o  m*/
 * 
 * <p>
 * For example, if the input type is {@code HashMap<String,Integer>} and the
 * input super class is {@code Map.class}, it will return the extended
 * parameterized type {@link Map}, but which retains the actual type
 * information from the original {@code HashMap}.
 * </p>
 * 
 * @param type
 *            class or parameterized type
 * @param superClass
 *            super class
 * @return matching parameterized type or {@code null}
 */
@SuppressWarnings({ "rawtypes" })
public static ParameterizedType getSuperParameterizedType(Type type, Class<?> superClass) {
    if (type instanceof Class<?> || type instanceof ParameterizedType) {
        TypeToken<?> typeToken = TypeToken.of(type);
        TypeSet types = typeToken.getTypes();

        if (types != null) {
            TypeSet set = superClass.isInterface() ? types.interfaces() : types.classes();
            Iterator iterator = set.iterator();

            while (iterator.hasNext()) {
                TypeToken tt = (TypeToken) iterator.next();
                if ((tt.getRawType() == superClass || superClass.isAssignableFrom(tt.getRawType()))
                        && tt.getType() instanceof ParameterizedType) {
                    return (ParameterizedType) tt.getType();
                }
            }
        }
    }
    return null;
}

From source file:com.google.api.server.spi.config.model.Serializers.java

public static List<Class<? extends Transformer<?, ?>>> getSerializerClasses(TypeToken<?> type,
        @Nullable final ApiSerializationConfig config) {
    if (type == null) {
        return Collections.emptyList();
    }//  w ww  . ja va  2s .c o  m

    List<Class<? extends Transformer<?, ?>>> allParentSerializers = Lists.newArrayList();
    List<TypeToken<?>> serializedTypes = Lists.newArrayList();
    for (TypeToken<?> typeToken : type.getTypes()) {
        ApiTransformer apiSerialization = typeToken.getRawType().getAnnotation(ApiTransformer.class);
        if (isSupertypeOf(typeToken, serializedTypes)) {
            continue;
        }
        if (apiSerialization != null) {
            allParentSerializers.add(apiSerialization.value());
            serializedTypes.add(typeToken);
        } else if (config != null) {
            ApiSerializationConfig.SerializerConfig serializerConfig = config.getSerializerConfig(typeToken);
            if (serializerConfig != null) {
                allParentSerializers.add(serializerConfig.getSerializer());
                serializedTypes.add(typeToken);
            }
        }
    }

    return allParentSerializers;
}

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
 *//*  w  w w .  j a v a 2s .c  o 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;
                    }
                }
            }
        }
    }
}

From source file:com.google.api.server.spi.MethodHierarchyReader.java

/**
 * Recursively builds a map from method_names to methods.  Method types will be resolved as much
 * as possible using {@code serviceType}.
 *
 * @param serviceType is the class object being inspected for service methods
 *//*from  w  w  w.ja v  a  2 s . co  m*/
private void buildServiceMethods(
        ImmutableListMultimap.Builder<EndpointMethod.ResolvedSignature, EndpointMethod> builder,
        TypeToken<?> serviceType) {
    for (TypeToken<?> typeToken : serviceType.getTypes().classes()) {
        Class<?> serviceClass = typeToken.getRawType();
        if (Object.class.equals(serviceClass)) {
            return;
        }
        for (Method method : serviceClass.getDeclaredMethods()) {
            if (!isServiceMethod(method)) {
                continue;
            }

            EndpointMethod currentMethod = EndpointMethod.create(endpointClass, method, typeToken);
            builder.put(currentMethod.getResolvedMethodSignature(), currentMethod);
        }
    }
}