开发者

Given a ParameterizedType, how do I create an instance of this type?

开发者 https://www.devze.com 2023-02-11 19:04 出处:网络
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 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消