父类
package com.itheima.mytest;
public class Person<T1, T2> {
}
子类
package com.itheima.mytest;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class Student extends Person<Integer, String> {
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
Student student = new Student();
// getClass() 获得该类的类类型(即类型变量)
Class clazz = student.getClass();
// getSuperclass() 获得该类的父类
System.out.println(clazz.getSuperclass());
// getGenericSuperclass() 获得该类带有泛型的父类
Type type = clazz.getGenericSuperclass();
System.out.println(type);
// Type是 Java 编程语言中所有类型的公共高级接口。它们包括原始类型、参数化类型、数组类型、类型变量和基本类型。
// ParameterizedType 参数化类型,即泛型
// 将Type转化为参数化类型(即泛型)
ParameterizedType p = (ParameterizedType) type;
// getActualTypeArguments() 获取参数化类型的数组,泛型可能有多个
Type[] actualTypeArguments = p.getActualTypeArguments();
// 将Type转化为类型变量(即Class)
Class c1 = (Class) actualTypeArguments[0];
Class c2 = (Class) actualTypeArguments[1];
System.out.println(c1);
System.out.println(c2);
}
}
运行结果
class com.itheima.mytest.Person
com.itheima.mytest.Person<java.lang.Integer, java.lang.String>
class java.lang.Integer
class
使用:
/**
*
*/
package com.idea.utils;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* 泛型工具
*
* @author zhailiang
*
*/
public class GenericUtils {
/**
* 获取目标class的第一个泛型参数的类型
*
* @param clazz
* @return
*/
@SuppressWarnings("rawtypes")
public static Class getGenericClass(Class clazz) {
return getGenericClass(clazz, 0);
}
/**
* 获取目标class的指定位置的泛型参数的类型
*
* @param clazz
* @param index
* 泛型参数的位置,第一个参数为0
* @return
*/
@SuppressWarnings("rawtypes")
public static Class getGenericClass(Class clazz, int index) {
Type t = clazz.getGenericSuperclass();
if (t instanceof ParameterizedType) {
Type[] params = ((ParameterizedType) t).getActualTypeArguments();
return (Class) params[index];
}
throw new RuntimeException("无法获得泛型的类型");
}
}
ClassUtils.isAssignable:是否可以转成某个类型
问题:某个方法 返回值是类型Object,但是实际上返回值 可能是List<Map> 或者是 Map(也就是返回一条还是多条Map),需要判断返回值是不是List,否则不能直接遍历;
解决办法:
- 工具类:ClassUtils
- 方法:isAssignable
- 参数1:Class<?> lhsType
- 参数2:Class<?> rhsType
- 简单理解:
- 参数1为 目标类型;
- 参数2为 不确定类型;
- 根据返回值 true/false来判断 rhsType 是不是 lhsType
补充:Assignable,可分配的,可转让的;