java使用反射获取泛型信息

落日映苍穹つ 2023-06-17 10:51 65阅读 0赞

ParameterizedType就是参数化类型的意思

解释

  1. 声明类型中带有“<>”的都是参数化类型,比如List<Integer>,Map<String,BigDecimal>
  2. getActualTypeArguments()返回Type[],即“<>”里的参数,比如Map<String,BigDecimal>
  3. getRawType()返回Tpye,得到“<>”前面的类型,比如List<String>
  4. getOwnerType()返回TypeO<T>.I<S>类型变量调用时会返回O<T>,比如Map.Entry<Long,Short>

代码

  1. import org.junit.Test;
  2. import java.lang.reflect.Field;
  3. import java.lang.reflect.ParameterizedType;
  4. import java.lang.reflect.Type;
  5. import java.math.BigDecimal;
  6. import java.util.Map;
  7. public class ReflectDemo {
  8. private static Map<String, BigDecimal>map;
  9. @Test
  10. public void test(){
  11. try {
  12. Class<?> aClass = Class.forName("com.test.annotation.param.ReflectDemo");
  13. //获取map属性对象
  14. Field field = aClass.getDeclaredField("map");
  15. //获取map属性的类型
  16. Type type = field.getGenericType();//返回属性声明的Type类型
  17. if (type instanceof ParameterizedType) {
  18. //强转为ParameterizedType对象
  19. ParameterizedType parameterizedType = (ParameterizedType) type;
  20. //获取原始类型
  21. Type rawType = parameterizedType.getRawType();
  22. System.out.println("map的原始类型为:"+rawType);
  23. //获取map的类型的所有泛型信息
  24. Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
  25. for(int i=0;i<actualTypeArguments.length;i++){
  26. System.out.println("Map类型的第"+(i+1)+"个泛型为:"+actualTypeArguments[i]);
  27. }
  28. }
  29. } catch (Exception e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. }

结果

在这里插入图片描述

项目中经常用的参数化类型ParameterizedType

  1. @RestController
  2. @RequestMapping("demo")
  3. public class AccountInfoController extends BaseController<AccountInfoBiz, AccountInfo, String> {
  4. @Autowired
  5. private AccountInfoMapper accountInfoMapper;
  6. @RequestMapping("type")
  7. public void type() {
  8. //获取AccountInfoController泛型列表中的实体全命名
  9. Class<AccountInfo> clazz = (Class<AccountInfo>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
  10. Example example = new Example(clazz);
  11. List<AccountInfo> list = accountInfoMapper.selectByExample(example);
  12. }
  13. }

发表评论

表情:
评论列表 (有 0 条评论,65人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java获取类型信息

    根据使用泛型位置的不同可以分为:声明侧泛型、使用侧泛型。 声明侧的泛型信息被记录在Class文件的Constant pool中以Signature的形式保存。而使用侧的泛型信