All Downloads are FREE. Search and download functionalities are using the official Maven repository.

matrix.boot.common.utils.ReflectUtil Maven / Gradle / Ivy

There is a newer version: 2.1.11
Show newest version
package matrix.boot.common.utils;

import matrix.boot.common.exception.ServiceException;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 反射工具类
 *
 * @author wangcheng
 * 2021/8/12
 **/
@SuppressWarnings("unchecked")
public class ReflectUtil {

    /**
     * 获取泛型中的参数类型
     *
     * @param clazz 类
     * @param index 第几个泛型
     * @return 泛型类型
     */
    public static  Class getGenericSuperClassTypes(Class clazz, Integer index) {
        if (clazz.isSynthetic()) {
            //泛型
            throw new ServiceException("lambda not support generic type");
        } else {
            Type[] types = ((ParameterizedType) clazz.getGenericSuperclass()).getActualTypeArguments();
            if (types[index] instanceof ParameterizedType) {
                ParameterizedType parameterizedTypes = (ParameterizedType) types[index];
                return (Class) parameterizedTypes.getRawType();
            }
            return (Class) types[index];
        }
    }

    /**
     * 初始化类
     *
     * @param className 类路径
     * @param tClazz    类类型
     * @param        泛型
     * @return 类实例
     */
    public static  T newInstance(String className, Class tClazz) {
        if (StringUtil.isEmpty(className)) {
            throw new ServiceException("className not be null!");
        }
        try {
            Class clazz = Class.forName(className);
            return (T) clazz.newInstance();
        } catch (Exception e) {
            throw new ServiceException(className + " instance failed");
        }
    }

    /**
     * 初始化类
     *
     * @param tClazz 类类型
     * @param     泛型
     * @return 类实例
     */
    public static  T newInstance(Class tClazz) {
        if (tClazz == null) {
            throw new ServiceException("tClazz not be null!");
        }
        try {
            return tClazz.newInstance();
        } catch (Exception e) {
            throw new ServiceException(tClazz + " instance failed");
        }
    }

//    /**
//     * 获取jdk unsafe类
//     * @return unsafe类
//     */
//    public static sun.misc.Unsafe getUnsafe() {
//        try {
//            Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
//            field.setAccessible(true);
//            return (sun.misc.Unsafe) field.get(null);
//        } catch (NoSuchFieldException | IllegalAccessException e) {
//            try {
//                Constructor unsafeConstructor = sun.misc.Unsafe.class.getDeclaredConstructor();
//                unsafeConstructor.setAccessible(true);
//                return unsafeConstructor.newInstance();
//            } catch (Exception e1) {
//                throw new ServiceException(e1);
//            }
//        }
//    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy