package com.lyq.util;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import org.apache.logging.log4j.core.layout.GelfLayout;
/**
* 泛型工具类
* @author Li Yongqiang
*/
public class GenericsUtils
{
/**
* 获取泛型的类型
* @param clazz
* @return Class
*/
@SuppressWarnings("unchecked")
public static Class getGenericType(Class clazz)
{
// Type genType = clazz.getGenericSuperclass();//得到泛型父类
Type[] types=clazz.getGenericInterfaces();
//System.out.println("genTYpe"+genType);//Object
ParameterizedType parameterizedType=(ParameterizedType)types[0];
clazz=(Class)parameterizedType.getActualTypeArguments()[0];
//Type[] types= ((ParameterizedType)genType).getActualTypeArguments();
// if (!(types[0] instanceof Class)) {
// return Object.class;
// }
// return (Class) types[0];
return clazz;
}
/**
* 获取对象的类名称
* @param clazz
* @return 类名称
*/
@SuppressWarnings("unchecked")
public static String getGenericName(Class clazz){
return clazz.getSimpleName();
}
}
异常如下:
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.lyq.dao.DaoSupport]: Constructor threw exception; nested exception is java.lang.ClassCastException: class sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to class java.lang.Class (sun.reflect.generics.reflectiveObjects.TypeVariableImpl and java.lang.Class are in module java.base of loader 'bootstrap')
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1147)
... 22 more
Caused by: java.lang.ClassCastException: class sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to class java.lang.Class (sun.reflect.generics.reflectiveObjects.TypeVariableImpl and java.lang.Class are in module java.base of loader 'bootstrap')
at com.lyq.util.GenericsUtils.getGenericType(GenericsUtils.java:29)
at com.lyq.dao.DaoSupport.<init>(DaoSupport.java:37)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
... 24 more