Search in sources :

Example 1 with TreeTraverser

use of com.google.common.collect.TreeTraverser in project Hystrix by Netflix.

the class TypeHelper method flattenTypeVariables.

/**
     * Unwinds parametrized type into plain list that contains all parameters for the given type including nested parameterized types,
     * for example calling the method for the following type
     * <code>
     * GType<GType<GDoubleType<GType<GDoubleType<Parent, Parent>>, Parent>>>
     * </code>
     * will return list of 8 elements:
     * <code>
     * [GType, GType, GDoubleType, GType, GDoubleType, Parent, Parent, Parent]
     * </code>
     * if the given type is not parametrized then returns list with one element which is given type passed into method.
     *
     * @param type the parameterized type
     * @return list of {@link Type}
     */
@ParametersAreNonnullByDefault
public static List<Type> flattenTypeVariables(Type type) {
    Validate.notNull(type, "type cannot be null");
    List<Type> types = new ArrayList<Type>();
    TreeTraverser<Type> typeTraverser = new TreeTraverser<Type>() {

        @Override
        public Iterable<Type> children(Type root) {
            if (root instanceof ParameterizedType) {
                ParameterizedType pType = (ParameterizedType) root;
                return Arrays.asList(pType.getActualTypeArguments());
            } else if (root instanceof TypeVariable) {
                TypeVariable pType = (TypeVariable) root;
                return Arrays.asList(pType.getBounds());
            }
            return Collections.emptyList();
        }
    };
    for (Type t : typeTraverser.breadthFirstTraversal(type)) {
        types.add(t);
    }
    return types;
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) WildcardType(java.lang.reflect.WildcardType) TypeVariable(java.lang.reflect.TypeVariable) TreeTraverser(com.google.common.collect.TreeTraverser) ArrayList(java.util.ArrayList) ParametersAreNonnullByDefault(javax.annotation.ParametersAreNonnullByDefault)

Aggregations

TreeTraverser (com.google.common.collect.TreeTraverser)1 ParameterizedType (java.lang.reflect.ParameterizedType)1 Type (java.lang.reflect.Type)1 TypeVariable (java.lang.reflect.TypeVariable)1 WildcardType (java.lang.reflect.WildcardType)1 ArrayList (java.util.ArrayList)1 ParametersAreNonnullByDefault (javax.annotation.ParametersAreNonnullByDefault)1