Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
 package com.yammer.dropwizard.util;
 
 
 import static com.google.common.base.Preconditions.checkNotNull;

Helper methods for class type parameters.

See also:
Super Type Tokens
public class Generics {
    private Generics() { /* singleton */ }

    
Finds the type parameter for the given class.

Parameters:
klass a parameterized class
Returns:
the class's type parameter
    public static Class<?> getTypeParameter(Class<?> klass) {
        return getTypeParameter(klassObject.class);
    }

    
Finds the type parameter for the given class which is assignable to the bound class.

Parameters:
klass a parameterized class
bound the type bound
<T> the type bound
Returns:
the class's type parameter
    @SuppressWarnings("unchecked")
    public static <T> Class<T> getTypeParameter(Class<?> klassClass<? super T> bound) {
        Type t = checkNotNull(klass);
        while (t instanceof Class<?>) {
            t = ((Class<?>) t).getGenericSuperclass();
        }
        /* This is not guaranteed to work for all cases with convoluted piping
         * of type parameters: but it can at least resolve straight-forward
         * extension with single type parameter (as per [Issue-89]).
         * And when it fails to do that, will indicate with specific exception.
         */
        if (t instanceof ParameterizedType) {
            // should typically have one of type parameters (first one) that matches:
            for (Type param : ((ParameterizedTypet).getActualTypeArguments()) {
                if (param instanceof Class<?>) {
                    final Class<T> cls = determineClass(boundparam);
                    if (cls != null) { return cls; }
                }
                else if (param instanceof TypeVariable) {
                    for (Type paramBound : ((TypeVariable<?>) param).getBounds()) {
                        if (paramBound instanceof Class<?>) {
                            final Class<T> cls = determineClass(boundparamBound);
                            if (cls != null) { return cls; }
                        }
                    }
                }
            }
        }
        throw new IllegalStateException("Cannot figure out type parameterization for " + klass.getName());
    }
    @SuppressWarnings("unchecked")
    private static <T> Class<T> determineClass(Class<? super T> boundType candidate) {
        if (candidate instanceof Class<?>) {
            final Class<?> cls = (Class<?>) candidate;
            if (bound.isAssignableFrom(cls)) {
                return (Class<T>) cls;
            }
        }
        return null;
    }
New to GrepCode? Check out our FAQ X