Given a ParameterizedType, how do I create an instance of this type?
I am retrieving a ParameterizedType object from Field.getGenericT开发者_StackOverflowype(), and I would like to create an instance of this type. This type might represent, for example, a HashMap.
I thought maybe I could cast it to a Class and then use newInstance(), but that caused a ClassCastException.
How do I do this?
ParameterizedType pType = ..;
((Class) pType.getRawType()).newInstance();
But you don't need the parameterized type for that - you can simple use field.getType()
. Use ParameterizedType
in case you want to create an instance of one of the type arguments.
精彩评论