Created
March 20, 2011 03:29
-
-
Save ryoasai/878041 to your computer and use it in GitHub Desktop.
Java's Type API sample showing how to obtain the actual type of parameterized type.
This file contains 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
import java.lang.reflect.Field; | |
import java.lang.reflect.GenericArrayType; | |
import java.lang.reflect.ParameterizedType; | |
import java.lang.reflect.Type; | |
import java.util.List; | |
public class GenericTypeSample { | |
public List<Integer>[] testField; | |
public static void main(String[] args) throws Exception { | |
new GenericTypeSample().run(); | |
} | |
public void run() throws Exception { | |
Field field = getClass().getField("testField"); | |
// Type of an array field is GenericArrayType | |
Type fieldType = field.getGenericType(); | |
assert fieldType instanceof GenericArrayType; | |
GenericArrayType genericArrayType = (GenericArrayType)fieldType; | |
// Array's component type can be obtained. | |
Type componentType = genericArrayType.getGenericComponentType(); | |
// In this case, the component type is ParameterizedType (List<Integer>). | |
assert componentType instanceof ParameterizedType; | |
// You can obtain actual type arguments from a ParameterizedType instance. | |
ParameterizedType parameterizedType = (ParameterizedType)componentType; | |
Type[] types = parameterizedType.getActualTypeArguments(); | |
assert types[0] == Integer.class; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment