Skip to content

Instantly share code, notes, and snippets.

@smilingleo
Created June 28, 2016 00:35
Show Gist options
  • Save smilingleo/7966a9c811053408f2aabab9feab6e83 to your computer and use it in GitHub Desktop.
Save smilingleo/7966a9c811053408f2aabab9feab6e83 to your computer and use it in GitHub Desktop.
a way to get actual parameter type
@Test
public void testJavaGeneric() {
// have to use a empty `{ }`, so that the `getClass().getGenericSuperclass()` will return a `ParameterizedType` instance.
List<Integer> list = new LinkedList<Integer>() {
};
// superclass contains the unerased info.
Type supers = list.getClass().getGenericSuperclass();
assertTrue(supers instanceof ParameterizedType);
ParameterizedType paramType = (ParameterizedType) supers;
Type[] actualTypes = paramType.getActualTypeArguments();
assertEquals(1, actualTypes.length);
assertEquals(Integer.class, actualTypes[0]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment