Here you can find the source of getGenericTypeArgumentFromGenericSuperType(Type genericSuperclass, Class
Parameter | Description |
---|---|
T | the generic type |
genericSuperclass | the generic superclass |
baseRequested | the base requested |
public static <T> Class<T> getGenericTypeArgumentFromGenericSuperType(Type genericSuperclass, Class<T> baseRequested)
//package com.java2s; // Licensed under the Apache License, Version 2.0 (the "License"); import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; public class Main { /**//from w ww . j ava 2 s . co m * Looks if generic supertype is paramized with given baseRequested. * * @param <T> the generic type * @param genericSuperclass the generic superclass * @param baseRequested the base requested * @return the generic type argument from generic super type. null if not found. */ //CHECKSTYLE.OFF FinalParameter Precondition cast public static <T> Class<T> getGenericTypeArgumentFromGenericSuperType(Type genericSuperclass, Class<T> baseRequested) { Type loopVar = genericSuperclass; while (loopVar != null && !(ParameterizedType.class.isAssignableFrom(loopVar.getClass()))) { loopVar = ((Class<?>) loopVar).getGenericSuperclass(); } if (loopVar != null && ParameterizedType.class.isAssignableFrom(loopVar.getClass())) { Type[] typeArgs = ((ParameterizedType) loopVar).getActualTypeArguments(); for (Type typeArg : typeArgs) { if (typeArg instanceof ParameterizedType) { typeArg = ((ParameterizedType) typeArg).getRawType(); } if ((typeArg instanceof Class) == false) { continue; } if (baseRequested.isAssignableFrom((Class<?>) typeArg) == false) { continue; } return (Class<T>) typeArg; } } return null; } }