public static Class < ? > getTypeArgument ( Class < ? > clazz , Class < ? > interfce ) { Map < Type , Type > resolvedTypes = new HashMap < Type , Type > ( ) ; Type type = clazz ; while ( ! declaresInterface ( getClass ( type ) , interfce ) ) { if ( type instanceof Class ) { type = ( ( Class < ? > ) type ) . getGenericSuperclass ( ) ; } else { ParameterizedType parameterizedType = ( ParameterizedType ) type ; Class < ? > rawType = ( Class < ? > ) parameterizedType . getRawType ( ) ; Type [ ] actualTypeArguments = parameterizedType . getActualTypeArguments ( ) ; TypeVariable < ? > [ ] typeParameters = rawType . getTypeParameters ( ) ; for ( int i = 0 ; i < actualTypeArguments . length ; i ++ ) { resolvedTypes . put ( typeParameters [ i ] , actualTypeArguments [ i ] ) ; } type = rawType . getGenericSuperclass ( ) ; } } Type actualTypeArgument ; if ( type instanceof Class ) { actualTypeArgument = ( ( Class < ? > ) type ) . getTypeParameters ( ) [ 0 ] ; } else { actualTypeArgument = ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) [ 0 ] ; } Class < ? > typeArgumentAsClass = null ; while ( resolvedTypes . containsKey ( actualTypeArgument ) ) { actualTypeArgument = resolvedTypes . get ( actualTypeArgument ) ; } typeArgumentAsClass = getClass ( actualTypeArgument ) ; return typeArgumentAsClass ; }
Get the actual type argument for a interface with one type