Java中获取泛型对象中的类型

在方法调用的时候,有时候需要传一个Class泛型过来。
但是,有时候,传过来的Class又是泛型。
比如下面代码

List

这时,传过去的只能是
List.class

此时就达不到我们想要的类型,List的效果。
在这里只要实现一个类就可以获取到List
public class DefaultTargetType {private Type type; private Class classType; @SuppressWarnings("unchecked") public DefaultTargetType() { Type superClass = getClass().getGenericSuperclass(); this.type = ((ParameterizedType) superClass).getActualTypeArguments()[0]; if (this.type instanceof ParameterizedType) { this.classType = (Class) ((ParameterizedType) this.type).getRawType(); } else { this.classType = (Class) this.type; } } }

结果:
Class> classType = new DefaultTargetType>() {}.getClassType();

就可以获取到泛型中的类型了。

作者:Se7end

声明:本博客文章为原创,只代表本人在工作学习中某一时间内总结的观点或结论。转载时请在文章页面明显位置给出原文链接。

【Java中获取泛型对象中的类型】转载于:https://www.cnblogs.com/se7end/p/11248540.html

    推荐阅读