前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >反射获取声明泛型工具类

反射获取声明泛型工具类

作者头像
阿超
发布2022-08-21 14:47:47
5140
发布2022-08-21 14:47:47
举报
文章被收录于专栏:快乐阿超

工具类:

代码语言:javascript
复制
public static Type[] getGenericTypes(Type paramType) {
    Type type;
    for (type = paramType; type instanceof Class;
         type = ((Class<?>) type).getGenericSuperclass()) {
        if (Object.class.equals(type)) {
            Type[] genericInterfaces = ((Class<?>) type).getGenericInterfaces();
            if (genericInterfaces.length > 0 && Objects.nonNull(genericInterfaces[0])) {
                type = genericInterfaces[0];
            }
        }
    }
    if (type instanceof ParameterizedType) {
        ParameterizedType ty = (ParameterizedType) type;
        return ty.getActualTypeArguments();
    }
    return new Type[0];
}

使用方式:

代码语言:javascript
复制
@Test
void testGetGenericTypes() {
    class StringArrayList extends ArrayList<String> {
        private static final long serialVersionUID = 5735314375293577082L;
    }
    Type[] stringType = ReflectHelper.getGenericTypes(new TypeReference<String>() {}.getClass());
    Assertions.assertEquals(String.class, stringType[0]);
    Type[] stringArrayListType = ReflectHelper.getGenericTypes(StringArrayList.class);
    Assertions.assertEquals(String.class, stringArrayListType[0]);
    Type[] hashMapType = ReflectHelper.getGenericTypes(new HashMap<String, Object>() {}.getClass());
    Assertions.assertEquals(String.class, hashMapType[0]);
    Assertions.assertEquals(Object.class, hashMapType[1]);
}

TypeReference

代码语言:javascript
复制
package io.github.vampireachao.stream.core.reflect;

import java.lang.reflect.Type;

/**
 * 单个泛型类型
 *
 * @author VampireAchao
 * @since 2022/6/2 18:53
 */
public abstract class TypeReference<T> implements Type {

    /**
     * Returns a string describing this type, including information
     * about any type parameters.
     *
     * @return a string describing this type
     * @implSpec The default implementation calls {@code toString}.
     * @since 1.8
     */
    @Override
    public String getTypeName() {
        return ReflectHelper.getGenericTypes(this.getClass())[0].getTypeName();
    }

    public Type getType() {
        return ReflectHelper.getGenericTypes(this.getClass())[0];
    }
}

完整源码:https://gitee.com/VampireAchao/stream-query/blob/master/stream-core/src/main/java/io/github/vampireachao/stream/core/reflect/ReflectHelper.java

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-07-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档