Last active
August 29, 2015 14:24
-
-
Save dyorgio/137d71a353f4c0a02f60 to your computer and use it in GitHub Desktop.
Get Actual Type Generic Argument
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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