Skip to content

Instantly share code, notes, and snippets.

@dyorgio
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dyorgio/137d71a353f4c0a02f60 to your computer and use it in GitHub Desktop.
Save dyorgio/137d71a353f4c0a02f60 to your computer and use it in GitHub Desktop.
Get Actual Type Generic Argument
public static Type getActualTypeArgument(Type type, Class topClass) {
if (type instanceof TypeVariable) {
TypeVariable typeVariable = (TypeVariable) type;
Class declareClass = topClass;
// find declare class
while (declareClass != null) {
if (((ParameterizedType) declareClass.getGenericSuperclass()).getRawType() == typeVariable.getGenericDeclaration()) {
break;
}
declareClass = declareClass.getSuperclass();
}
if (declareClass != null) {
int index = -1;
int internalIndex = 0;
for (TypeVariable variable : declareClass.getSuperclass().getTypeParameters()) {
if (variable == typeVariable) {
index = internalIndex;
break;
}
internalIndex++;
}
if (index != -1) {
return ((ParameterizedType) declareClass.getGenericSuperclass()).getActualTypeArguments()[index];
}
}
}
return type;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment