Example usage for java.lang.reflect ParameterizedType getActualTypeArguments

List of usage examples for java.lang.reflect ParameterizedType getActualTypeArguments

Introduction

In this page you can find the example usage for java.lang.reflect ParameterizedType getActualTypeArguments.

Prototype

Type[] getActualTypeArguments();

Source Link

Document

Returns an array of Type objects representing the actual type arguments to this type.

Usage

From source file:com.holonplatform.core.internal.utils.TypeUtils.java

/**
 * Return the type parameter of a generic type.
 * @param clazz subClass of <code>baseClass</code> to analyze.
 * @param baseClass base class having the type parameter the value of which we need to retrieve
 * @return the parameterized type value//from  w w w . ja  v  a2  s  .  co m
 */
@SuppressWarnings("rawtypes")
public static Type getTypeArgument(Class<?> clazz, Class<?> baseClass) {
    Stack<Type> superclasses = new Stack<>();
    Type currentType;
    Class<?> currentClass = clazz;

    if (clazz.getGenericSuperclass() == Object.class) {
        currentType = clazz;
        superclasses.push(currentType);
    } else {

        do {
            currentType = currentClass.getGenericSuperclass();
            superclasses.push(currentType);
            if (currentType instanceof Class) {
                currentClass = (Class) currentType;
            } else if (currentType instanceof ParameterizedType) {
                currentClass = (Class) ((ParameterizedType) currentType).getRawType();
            }
        } while (!currentClass.equals(baseClass));

    }

    // find which one supplies type argument and return it
    TypeVariable tv = baseClass.getTypeParameters()[0];
    while (!superclasses.isEmpty()) {
        currentType = superclasses.pop();

        if (currentType instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) currentType;
            Class<?> rawType = (Class) pt.getRawType();
            int argIndex = Arrays.asList(rawType.getTypeParameters()).indexOf(tv);
            if (argIndex > -1) {
                Type typeArg = pt.getActualTypeArguments()[argIndex];
                if (typeArg instanceof TypeVariable) {
                    // type argument is another type variable - look for the value of that
                    // variable in subclasses
                    tv = (TypeVariable) typeArg;
                    continue;
                } else {
                    // found the value - return it
                    return typeArg;
                }
            }
        }

        // needed type argument not supplied - break and throw exception
        break;
    }
    throw new IllegalArgumentException(currentType + " does not specify a type parameter");
}

From source file:jp.terasoluna.fw.util.GenericsUtil.java

/**
 * ?????/*w ww .j  a  v  a  2s  .c om*/
 * <p>
 * <h5>??????</h5> ?????????????? ?????? ?????????? ?<code>WildCardType</code>?
 * ????????????? ???????????
 * <ul>
 * <li>????(???????) <code><pre>
 *     public class Descendant extends Generic&lt;String, Integer&gt; {
 *        ...
 *     }
 *     </pre></code> ???????[<code>String</code>, <code>Integer</code>]? ??????</li>
 * <li>????(????????) <code><pre>
 *     public class Descendant extends Generic&lt;String[], Integer&gt; {
 *        ...
 *     }
 *     </pre></code> ???????[<code>String[]</code>, <code>Integer</code>]? ??????</li>
 * <li>????(?????????) <code><pre>
 *     public class Descendant
 *         extends Generic&lt;String[], Map&lt;String, Object&gt;&gt; {
 *        ...
 *     }
 *     </pre></code> ???????[<code>String[]</code>, <code>Map</code>]? ??????</li>
 * <li>??????(???????) <code><pre>
 *     public class Descendant&lt;P, Q&gt; extends Generic&lt;S, T&gt; {
 *        ...
 *     }
 *     </pre></code></li>
 * <li>??????(???????) <code><pre>
 *     public class Descendant&lt;P extends String, Q super Bean&gt;
 *         extends Generic&lt;S, T&gt; {
 *        ...
 *     }
 *     </pre></code></li>
 * <li>??????(?????) <code><pre>
 *     Generic&lt;String, Integer&gt; descendant =
 *         new Generic&lt;String, Integer&gt;();
 *     </pre></code></li>
 * </ul>
 * </p>
 * <p>
 * <h5>??</h5> <code>genericType</code>?<code>descendantClass</code>?? ??????????????
 * <ul>
 * <li>? <code><pre>
 *       public class Child&lt;S, T&gt; extends Generic&lt;S, T&gt; {
 *          ...
 *       }
 *
 *       public class GrandChild&lt;S, T&gt; extends Child&lt;S, T&gt; {
 *          ...
 *       }
 *
 *       public class Descendant extends GrandChild&lt;String, Integer&gt; {
 *          ...
 *       }
 * </pre></code> ???????[<code>String</code>, <code>Integer</code>]? ??????</li>
 * </ul>
 * </p>
 * <p>
 * <h5>?????</h5> <code>genericType</code>?<code>descendantClass</code>??? ???????????
 * <code>genercClass</code>?????????
 * <ul>
 * <li>???? <code><pre>
 *       public class Generic&lt;S, T&gt; {
 *          ...
 *       }
 *
 *       public class Child&lt;A, T, B, S&gt; extends Generic&lt;S, T&gt; {
 *          ...
 *       }
 *
 *       public class Descendant
 *            extends Generic&lt;Boolean, Integer, Double, String&gt; {
 *          ...
 *       }
 * </pre></code> ???????[<code>String</code>, <code>Integer</code>]? ??????</li>
 * </ul>
 * </p>
 * @param <T> ???
 * @param genericClass ??
 * @param descendantClass <code>genericsClass</code>?? ???
 * @return ??<code>Class</code>?? ?<code>genercClass</code>?????
 * @throws IllegalArgumentException <code>genericClass</code>? <code>null</code>?? <code>descendantClass</code>?
 *             <code>null</code>??
 * @throws IllegalStateException <code>descendantClass</code>??? ????????? <code>genercClass</code>
 *             ????? ?????
 */
@SuppressWarnings("rawtypes")
public static <T> Class[] resolveParameterizedClass(Class<T> genericClass, Class<? extends T> descendantClass)
        throws IllegalArgumentException, IllegalStateException {
    if (genericClass == null) {
        throw new IllegalArgumentException("Argument 'genericsClass' (" + Class.class.getName() + ") is null");
    }
    if (descendantClass == null) {
        throw new IllegalArgumentException("Argument 'descendantClass'(" + Class.class.getName() + ") is null");
    }

    List<ParameterizedType> ancestorTypeList = getAncestorTypeList(genericClass, descendantClass);

    ParameterizedType parameterizedType = ancestorTypeList.get(ancestorTypeList.size() - 1);
    // parameterizedType??? Type ??
    // AbstractBLogic<P, R>??P?R
    Type[] actualTypes = parameterizedType.getActualTypeArguments();

    // ??????
    Class[] actualClasses = new Class[actualTypes.length];
    for (int i = 0; i < actualTypes.length; i++) {
        // actualTypes[i]i?
        // ancestorList????
        actualClasses[i] = resolveTypeVariable(actualTypes[i], ancestorTypeList);
    }
    return actualClasses;
}

From source file:jp.terasoluna.fw.util.GenericsUtil.java

/**
 * ????/*from  w w  w  .  j ava2  s  .c  o  m*/
 * <p>
 * <h5>??????</h5> ?????????????? ?????? ?????????? ?<code>WildCardType</code>?
 * ????????????? ???????????
 * <ul>
 * <li>????(???????) <code><pre>
 *     public class Descendant extends Generic&lt;String, Integer&gt; {
 *        ...
 *     }
 *     </pre></code> ???????<code>String</code>???<code>Integer</code>? ????</li>
 * <li>????(????????) <code><pre>
 *     public class Descendant extends Generic&lt;String[], Integer&gt; {
 *        ...
 *     }
 *     </pre></code> ???????<code>String[]</code>???<code>Integer</code>? ????</li>
 * <li>????(?????????) <code><pre>
 *     public class Descendant
 *         extends Generic&lt;String[], Map&lt;String, Object&gt;&gt; {
 *        ...
 *     }
 *     </pre></code> ???????<code>String[]</code>???<code>Map</code> ?????</li>
 * <li>??????(???????) <code><pre>
 *     public class Descendant&lt;P, Q&gt; extends Generic&lt;S, T&gt; {
 *        ...
 *     }
 *     </pre></code></li>
 * <li>??????(???????) <code><pre>
 *     public class Descendant&lt;P extends String, Q super Bean&gt;
 *         extends Generic&lt;S, T&gt; {
 *        ...
 *     }
 *     </pre></code></li>
 * <li>??????(?????) <code><pre>
 *     Generic&lt;String, Integer&gt; descendant =
 *         new Generic&lt;String, Integer&gt;();
 *     </pre></code></li>
 * </ul>
 * </p>
 * <p>
 * <h5>??</h5> <code>genericType</code>?<code>descendantClass</code>?? ??????????????
 * <ul>
 * <li>? <code><pre>
 *       public class Child&lt;S, T&gt; extends Generic&lt;S, T&gt; {
 *          ...
 *       }
 *
 *       public class GrandChild&lt;S, T&gt; extends Child&lt;S, T&gt; {
 *          ...
 *       }
 *
 *       public class Descendant extends GrandChild&lt;String, Integer&gt; {
 *          ...
 *       }
 * </pre></code> ???????<code>String</code>???<code>Integer</code> ?????</li>
 * </ul>
 * </p>
 * <p>
 * <h5>?????</h5> <code>genericType</code>?<code>descendantClass</code>??? ???????????
 * <code>genercClass</code>?????????
 * <ul>
 * <li>???? <code><pre>
 *       public class Generic&lt;S, T&gt; {
 *          ...
 *       }
 *
 *       public class Child&lt;A, T, B, S&gt; extends Generic&lt;S, T&gt; {
 *          ...
 *       }
 *
 *       public class Descendant
 *            extends Generic&lt;Boolean, Integer, Double, String&gt; {
 *          ...
 *       }
 * </pre></code> ???????<code>String</code>???<code>Integer</code> ?????</li>
 * </ul>
 * </p>
 * @param <T> ???
 * @param genericClass ??
 * @param descendantClass <code>genericsClass</code>?? ???
 * @param index ?????
 * @return ??<code>Class</code>
 * @throws IllegalArgumentException <code>genericClass</code>? <code>null</code>?? <code>descendantClass</code>?
 *             <code>null</code>?? <code>index</code>?<code>0</code>???????? ????
 * @throws IllegalStateException <code>descendantClass</code>??? ????????? <code>genercClass</code>
 *             ????? ?????
 */
public static <T> Class<? extends Object> resolveParameterizedClass(Class<T> genericClass,
        Class<? extends T> descendantClass, int index) throws IllegalArgumentException, IllegalStateException {
    if (genericClass == null) {
        throw new IllegalArgumentException("Argument 'genericsClass' (" + Class.class.getName() + ") is null");
    }
    if (descendantClass == null) {
        throw new IllegalArgumentException("Argument 'descendantClass'(" + Class.class.getName() + ") is null");
    }

    List<ParameterizedType> ancestorTypeList = getAncestorTypeList(genericClass, descendantClass);

    ParameterizedType parameterizedType = ancestorTypeList.get(ancestorTypeList.size() - 1);
    // parameterizedType??? Type ??
    // AbstractBLogic<P, R>??P?R
    Type[] actualTypes = parameterizedType.getActualTypeArguments();

    // ??????
    if (index < 0 || index >= actualTypes.length) {
        throw new IllegalArgumentException("Argument 'index'(" + Integer.toString(index)
                + ") is out of bounds of" + " generics parameters");
    }

    // actualTypes[index]index?
    // ancestorList????
    return resolveTypeVariable(actualTypes[index], ancestorTypeList);
}

From source file:org.jiemamy.utils.reflect.GenericUtil.java

/**
 * ??(???)??????? {@code map}??//from  ww w  .  ja  v  a2  s  .  c om
 * 
 * @param type 
 * @param map ????????{@link Map}
 * @throws IllegalArgumentException ?{@code null}???
 */
protected static void gatherTypeVariables(Type type, Map<TypeVariable<?>, Type> map) {
    Validate.notNull(type);
    Validate.notNull(map);
    if (ParameterizedType.class.isInstance(type)) {
        ParameterizedType parameterizedType = ParameterizedType.class.cast(type);
        TypeVariable<?>[] typeVariables = GenericDeclaration.class.cast(parameterizedType.getRawType())
                .getTypeParameters();
        Type[] actualTypes = parameterizedType.getActualTypeArguments();
        for (int i = 0; i < actualTypes.length; ++i) {
            map.put(typeVariables[i], actualTypes[i]);
        }
    }
}

From source file:eu.stratosphere.api.java.typeutils.TypeExtractor.java

private static TypeInformation<?> findCorrespondingInfo(TypeVariable<?> typeVar, Type type,
        TypeInformation<?> corrInfo) {
    if (type instanceof TypeVariable) {
        TypeVariable<?> variable = (TypeVariable<?>) type;
        if (variable.getName().equals(typeVar.getName())
                && variable.getGenericDeclaration().equals(typeVar.getGenericDeclaration())) {
            return corrInfo;
        }/*ww w . jav  a  2s.  c om*/
    } else if (type instanceof ParameterizedType
            && Tuple.class.isAssignableFrom((Class<?>) ((ParameterizedType) type).getRawType())) {
        ParameterizedType tuple = (ParameterizedType) type;
        Type[] args = tuple.getActualTypeArguments();

        for (int i = 0; i < args.length; i++) {
            TypeInformation<?> info = findCorrespondingInfo(typeVar, args[i],
                    ((TupleTypeInfo<?>) corrInfo).getTypeAt(i));
            if (info != null) {
                return info;
            }
        }
    }
    return null;
}

From source file:net.jodah.typetools.TypeResolver.java

/**
 * Populates the {@code map} with variable/argument pairs for the given {@code type}.
 */// www  .j av a 2  s  .c o m
private static void populateTypeArgs(ParameterizedType type, Map<TypeVariable<?>, Type> map,
        boolean depthFirst) {
    if (type.getRawType() instanceof Class) {
        TypeVariable<?>[] typeVariables = ((Class<?>) type.getRawType()).getTypeParameters();
        Type[] typeArguments = type.getActualTypeArguments();

        if (type.getOwnerType() != null) {
            Type owner = type.getOwnerType();
            if (owner instanceof ParameterizedType)
                populateTypeArgs((ParameterizedType) owner, map, depthFirst);
        }

        for (int i = 0; i < typeArguments.length; i++) {
            TypeVariable<?> variable = typeVariables[i];
            Type typeArgument = typeArguments[i];

            if (typeArgument instanceof Class) {
                map.put(variable, typeArgument);
            } else if (typeArgument instanceof GenericArrayType) {
                map.put(variable, typeArgument);
            } else if (typeArgument instanceof ParameterizedType) {
                map.put(variable, typeArgument);
            } else if (typeArgument instanceof TypeVariable) {
                TypeVariable<?> typeVariableArgument = (TypeVariable<?>) typeArgument;
                if (depthFirst) {
                    Type existingType = map.get(variable);
                    if (existingType != null) {
                        map.put(typeVariableArgument, existingType);
                        continue;
                    }
                }

                Type resolvedType = map.get(typeVariableArgument);
                if (resolvedType == null)
                    resolvedType = resolveBound(typeVariableArgument);
                map.put(variable, resolvedType);
            }
        }
    }
}

From source file:org.soybeanMilk.SbmUtils.java

/**
 * //ww  w  .j a v  a2s.c o m
 * @param type
 * @param variableTypesMap
 * @return
 * @date 2012-5-14
 */
private static Type reifyInner(Type type, Map<TypeVariable<?>, Type> variableTypesMap) {
    Type result = null;

    if (type instanceof Class<?>) {
        result = type;
    } else if (type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;

        Type[] at = pt.getActualTypeArguments();
        Type[] cat = new Type[at.length];

        //pt?pt??
        boolean reified = true;
        for (int i = 0; i < at.length; i++) {
            cat[i] = reifyInner(at[i], variableTypesMap);

            if (cat[i] != at[i])
                reified = false;
        }

        if (reified)
            result = pt;
        else
            result = new CustomParameterizedType(pt.getRawType(), pt.getOwnerType(), cat);
    } else if (type instanceof GenericArrayType) {
        GenericArrayType gap = (GenericArrayType) type;

        Type ct = gap.getGenericComponentType();
        Type cct = reifyInner(ct, variableTypesMap);

        if (cct == ct)
            result = gap;
        else
            result = new CustomGenericArrayType(cct);
    } else if (type instanceof TypeVariable<?>) {
        TypeVariable<?> tv = (TypeVariable<?>) type;

        if (variableTypesMap != null)
            result = variableTypesMap.get(tv);

        if (result == null) {
            Type[] bounds = tv.getBounds();

            if (bounds == null || bounds.length == 0)
                result = Object.class;
            else
                result = bounds[0];
        }

        result = reifyInner(result, variableTypesMap);
    } else if (type instanceof WildcardType) {
        WildcardType wt = (WildcardType) type;

        Type[] upperBounds = wt.getUpperBounds();

        Type upperType = (upperBounds != null && upperBounds.length > 0 ? upperBounds[0] : null);

        if (upperType == null)
            upperType = Object.class;

        result = reifyInner(upperType, variableTypesMap);
    } else
        result = type;

    return result;
}

From source file:GenericsUtil.java

/**
 * Returns the class defined for the type variable
 * of the given name. // w w  w  .jav a  2s. co  m
 * @param clazz the class
 * @param genericClazz the generic class or interface to check the type for
 * @param name the name of the type variable
 * @param recursive whether or not to recurse up the
 * object's inheritance hierarchy.
 * @return the class
 */
public static Class<?> getTypeVariableClassByName(Class<?> clazz, Type genericClazz, String name,
        Boolean recursive) {

    // we hit the end of the line here :)
    if (clazz == null || clazz.equals(Object.class)) {
        return null;
    }

    // loop through all of the types implemented
    for (ParameterizedType pType : getGenericTypes(clazz)) {

        // do all of them, or one of them
        if (genericClazz == null || genericClazz.equals(pType.getRawType())) {

            // get super class type variables
            TypeVariable<?>[] typeVars = getGenericTypeParameters(clazz, pType.getRawType());
            for (int i = 0; i < typeVars.length; i++) {
                if ((genericClazz == null || genericClazz.equals(typeVars[i].getGenericDeclaration()))
                        && typeVars[i].getName().equals(name)) {

                    // get the type
                    Type type = pType.getActualTypeArguments()[i];

                    if (Class.class.isAssignableFrom(type.getClass())) {
                        return (Class<?>) type;
                    } else if (ParameterizedType.class.isAssignableFrom(type.getClass())) {
                        return (Class<?>) ((ParameterizedType) type).getRawType();
                    }
                }
            }

        }

    }

    // none found
    return (recursive) ? getTypeVariableClassByName(clazz.getSuperclass(), genericClazz, name, recursive)
            : null;
}

From source file:com.android.camera2.its.ItsSerializer.java

@SuppressWarnings("unchecked")
public static JSONObject serialize(CameraMetadata md) throws ItsException {
    JSONObject jsonObj = new JSONObject();
    Field[] allFields = md.getClass().getDeclaredFields();
    if (md.getClass() == TotalCaptureResult.class) {
        allFields = CaptureResult.class.getDeclaredFields();
    }// www  .  jav  a2  s.  c o m
    for (Field field : allFields) {
        if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())
                && (field.getType() == CaptureRequest.Key.class || field.getType() == CaptureResult.Key.class
                        || field.getType() == TotalCaptureResult.Key.class
                        || field.getType() == CameraCharacteristics.Key.class)
                && field.getGenericType() instanceof ParameterizedType) {
            ParameterizedType paramType = (ParameterizedType) field.getGenericType();
            Type[] argTypes = paramType.getActualTypeArguments();
            if (argTypes.length > 0) {
                try {
                    Type keyType = argTypes[0];
                    Object keyObj = field.get(md);
                    MetadataEntry entry;
                    if (keyType instanceof GenericArrayType) {
                        entry = serializeArrayEntry(keyType, keyObj, md);
                    } else {
                        entry = serializeEntry(keyType, keyObj, md);
                    }

                    // TODO: Figure this weird case out.
                    // There is a weird case where the entry is non-null but the toString
                    // of the entry is null, and if this happens, the null-ness spreads like
                    // a virus and makes the whole JSON object null from the top level down.
                    // Not sure if it's a bug in the library or I'm just not using it right.
                    // Workaround by checking for this case explicitly and not adding the
                    // value to the jsonObj when it is detected.
                    if (entry != null && entry.key != null && entry.value != null
                            && entry.value.toString() == null) {
                        Logt.w(TAG, "Error encountered serializing value for key: " + entry.key);
                    } else if (entry != null) {
                        jsonObj.put(entry.key, entry.value);
                    } else {
                        // Ignore.
                    }
                } catch (IllegalAccessException e) {
                    throw new ItsException("Access error for field: " + field + ": ", e);
                } catch (org.json.JSONException e) {
                    throw new ItsException("JSON error for field: " + field + ": ", e);
                }
            }
        }
    }
    return jsonObj;
}

From source file:Main.java

/**
 * get generic class by actual type argument index.
 *///  w  w w  .j  a  va  2  s . c  o  m
public static Class<?> getGenericClass(Class<?> cls, int actualTypeArgIndex) {
    try {
        ParameterizedType parameterizedType;
        if (cls.getGenericInterfaces().length > 0
                && cls.getGenericInterfaces()[0] instanceof ParameterizedType) {
            parameterizedType = ((ParameterizedType) cls.getGenericInterfaces()[0]);
        } else if (cls.getGenericSuperclass() instanceof ParameterizedType) {
            parameterizedType = (ParameterizedType) cls.getGenericSuperclass();
        } else {
            parameterizedType = null;
        }
        if (parameterizedType != null) {
            Object genericClass = parameterizedType.getActualTypeArguments()[actualTypeArgIndex];
            if (genericClass instanceof ParameterizedType) {
                return (Class<?>) ((ParameterizedType) genericClass).getRawType();
            } else if (genericClass instanceof GenericArrayType) {
                Class<?> componentType = (Class<?>) ((GenericArrayType) genericClass).getGenericComponentType();
                if (componentType.isArray()) {
                    return componentType;
                } else {
                    return Array.newInstance(componentType, 0).getClass();
                }
            } else if (genericClass instanceof Class) {
                return (Class<?>) genericClass;
            }
        }
    } catch (Exception e) {
    }
    if (cls.getSuperclass() != null && cls.getSuperclass() != Object.class) {
        return getGenericClass(cls.getSuperclass(), actualTypeArgIndex);
    } else {
        throw new IllegalArgumentException(cls.getName() + " generic type undefined!");
    }
}