public static Class < ? > getGenericTypeArgument ( Field field ) { // TODO Might this better be located under SPI in an "InjectionUtil" class or something? Type genericType = field . getGenericType ( ) ; if ( genericType instanceof ParameterizedType ) { ParameterizedType parameterizedType = ( ParameterizedType ) genericType ; Type [ ] actualTypeArguments = parameterizedType . getActualTypeArguments ( ) ; if ( actualTypeArguments . length == 1 ) { Type type = actualTypeArguments [ 0 ] ; if ( type instanceof Class < ? > ) { Class < ? > realClass = ( Class < ? > ) type ; return realClass ; } else { throw new IllegalArgumentException ( "only direct class types are allowed for generic parameter on field " + field . getName ( ) + " of type " + genericType . getClass ( ) . getName ( ) + "<T>, but " + type + " was given!" ) ; } } else { throw new IllegalArgumentException ( "only one type parameter expected for field " + field . getName ( ) + " but " + actualTypeArguments . length + " where found!" ) ; } } else { throw new IllegalArgumentException ( "The field '" + field . getName ( ) + "' is not a ParameterizedType but this is required for type inferrence!" ) ; } }
Takes a field and returns the type argument for this