获取泛型的数据类型

╰+攻爆jí腚メ 2022-11-28 13:25 270阅读 0赞
  1. public static void main(String[] args) {
  2. // Type type=getGenericType(AE_C11.class, TestInterface.class,0);
  3. Type type=getGenericType(TextField.class, HasValueAndElement.class,1);
  4. System.out.println(type);
  5. }
  6. public static Type getGenericType(Class<?> clazz, Class<?> interest, int index) {
  7. //判断该类是否实现了HasVaue接口
  8. if (clazz == null || clazz == Object.class || interest == null || !interest.isAssignableFrom(clazz)) {
  9. return null;
  10. }
  11. //获取实现的接口
  12. Class<?>[] interfaces = clazz.getInterfaces();
  13. //判断长度,如果为空,则该类没有实现的接口
  14. int i=0;
  15. if (interfaces.length!=0) {
  16. for (Class<?> inter : interfaces) {
  17. //循环判断实现的接口是否实现了interest接口
  18. Type type=getIntfaceGenericType(clazz,inter,interest,index,i);
  19. if (type!=null){
  20. return type;
  21. }
  22. i++;
  23. }
  24. }
  25. //获取实现的接口,判断该接口
  26. // Type[] types = clazz.getGenericInterfaces();
  27. //获取继承的父类,判断该父类
  28. Type type=clazz.getGenericSuperclass();
  29. try {
  30. ParameterizedType supclassType= (ParameterizedType) type;
  31. return supclassType.getActualTypeArguments()[index];
  32. }catch (Exception e){
  33. //该类的父类不符合条件,对父类进行操作
  34. return getGenericType(clazz.getSuperclass(),interest,index);
  35. }
  36. }
  37. public static Type getIntfaceGenericType(Class<?> old,Class<?> clazz, Class<?> interest, int index,int i){
  38. //判断该接口是否继承了interest
  39. if (clazz==interest){
  40. Type[] types=old.getGenericInterfaces();
  41. System.out.println(types[i]);
  42. ParameterizedType para1= (ParameterizedType) types[i];
  43. return para1.getActualTypeArguments()[index];
  44. // for(Type type:types){
  45. // ParameterizedType para= (ParameterizedType) type;
  46. // return para.getActualTypeArguments()[index];
  47. // }
  48. }
  49. if (interest.isAssignableFrom(clazz)) {
  50. //判断该接口是否具备第index个泛型
  51. Type[] types=clazz.getGenericInterfaces();
  52. for (Type type:types){
  53. try {
  54. System.out.println((Class<?>)type);
  55. if (interest.isAssignableFrom((Class<?>)type)){
  56. ParameterizedType parameterizedType = (ParameterizedType) type;
  57. Type actualTypeArgument = parameterizedType.getActualTypeArguments()[index];
  58. return actualTypeArgument;
  59. }
  60. }catch (ClassCastException e){
  61. //获取该接口继承的接口并进行判断
  62. Class<?>[] interfaces = clazz.getInterfaces();
  63. int j=0;
  64. for (Class<?> in:interfaces){
  65. Type intfaceGenericType = getIntfaceGenericType(clazz, in, interest, index, j);
  66. if (intfaceGenericType!=null){
  67. return intfaceGenericType;
  68. }
  69. j++;
  70. }
  71. }
  72. }
  73. }
  74. return null;
  75. }

发表评论

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

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

相关阅读

    相关 Java获取类型信息

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