获取在接口或者类上定义的泛型类型
来源:互联网 发布:js 字段包含某些值 编辑:程序博客网 时间:2024/06/05 12:49
通过Class类上的 getGenericSuperclass() 或者 getGenericInterfaces() 获取父类或者接口的类型,然后通过ParameterizedType.getActualTypeArguments()
可以得到定义在类或者接口上的泛型类型,具体参考如下代码:
/* * To change this template use File | Settings | Editor | File and Code Templates */import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;public class GenericTypeTest { static class Test1 extends T<Person, Animal> { } static class Test2 implements I<Person, Animal>, I2<Fruit> { } public static void main(String[] args) { //获取类定义上的泛型类型 Test1 test1 = new Test1(); Type types = test1.getClass().getGenericSuperclass(); Type[] genericType = ((ParameterizedType) types).getActualTypeArguments(); for (Type t : genericType) { System.out.println(t.getTypeName()); } System.out.println("==============================================="); //获取接口定义上的泛型类型 Test2 test2 = new Test2(); //一个类可能实现多个接口,每个接口上定义的泛型类型都可取到 Type[] interfacesTypes = test2.getClass().getGenericInterfaces(); for (Type t : interfacesTypes) { Type[] genericType2 = ((ParameterizedType) t).getActualTypeArguments(); for (Type t2 : genericType2) { System.out.println(t2.getTypeName()); } } }}class T<T1, T2> { public void printT(T1 t1, T2 t2) { System.out.println(t1.getClass()); System.out.println(t2.getClass()); }}interface I<T1, T2> {}interface I2<K> {}class Person { @Override public String toString() { return "Person Type"; }}class Animal { @Override public String toString() { return "Animal Type"; }}class Fruit { @Override public String toString() { return "Fruit Type"; }}
转自:https://www.cnblogs.com/jiaoyiping/p/6130355.html
阅读全文
0 0
- 获取在接口或者类上定义的泛型类型
- 泛类型定义在接口上
- 泛型接口的实现方式一:在子类的定义上声明泛型类型
- 当泛型定义在接口上!!!
- 泛型定义在接口上
- Java 泛型定义在接口上
- 将泛型定义在类上和定义在接口上的区别!!!(包括静态)
- 如何定一个只能在堆上或者只能在栈上定义的类
- 获取接口的泛型类型
- 如何定义一个只能在栈或者堆上生成的类
- 泛型定义在接口
- 泛型定义在类上
- 【泛型】接口上定义泛型
- #define和typedef在定义指针类型上的优劣
- 面向对象定义类或者接口
- Base公共接口实现泛型的类型获取
- 黑马程序员_日记51_泛型定义在接口上
- 获取实现泛型接口的具体类的实现的类型
- Idea 自动生成变量set方法插件
- 导出Excel(.NET 代码)
- jvm 学习
- iOS 11.0之后,UIScrollView顶部空20像素
- 安卓智能地图开发与实施二十三:三维场景中的可视化
- 获取在接口或者类上定义的泛型类型
- 截取两个String字符串中间的字符串
- crypto++RSA数字签名
- 数据流_小记
- AES加密方式整理
- Markdown编辑之图片去水印
- DB2中的空值和NULL处理
- 升级到 Android Studio 3.0 + Gradle 4.1 遇到的一些坑及解决方案
- dubbo源码解析