开发者

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜